Centoschina

项目要求

爬取centoschina_cn的所有问题,包括文章标题和内容

数据库表设计

库表设计:

数据展示:

项目亮点

  • 低耦合,高内聚。

    爬虫专有settings

    custom_settings = custom_settings_for_centoschina_cn
    custom_settings_for_centoschina_cn = {
    'MYSQL_USER': 'root',
    'MYSQL_PWD': '123456',
    'MYSQL_DB': 'questions',
    }
  • DownloaderMiddleware使用

    class CentoschinaDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects. @classmethod
    def from_crawler(cls, crawler):
    # This method is used by Scrapy to create your spiders.
    s = cls()
    crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
    return s # 处理请求
    def process_request(self, request, spider):
    # Called for each request that goes through the downloader
    # middleware. # Must either:
    # - return None: continue processing this request 继续执行下一步操作,不处理默认返回None
    # - or return a Response object 直接返回响应, 如scrapy和pyppeteer不需要用下载器中间件访问外网,直接返回响应, pyppeteer有插件,一般和scrapy还能配合,selenium不行,没有插件
    # - or return a Request object 将请求返回到schdular的调度队列中供以后重新访问
    # - or raise IgnoreRequest: process_exception() methods of
    # installed downloader middleware will be called
    return None # 处理响应
    def process_response(self, request, response, spider):
    # Called with the response returned from the downloader. # Must either;
    # - return a Response object 返回响应结果
    # - return a Request object 结果不对(判断结果对不对一般判断状态码和内容大小)一般返回request,也是将请求返回到schdular的调度队列中供以后重新访问
    # - or raise IgnoreRequest
    return response # 处理异常:如超时错误等
    def process_exception(self, request, exception, spider):
    # Called when a download handler or a process_request()
    # (from other downloader middleware) raises an exception. # Must either:
    # - return None: continue processing this exception 继续执行下一步,没有异常
    # - return a Response object: stops process_exception() chain 如果其返回一个 Response 对象,则已安装的中间件链的 process_response() 方法被调用。Scrapy将不会调用任何其他中间件的 process_exception() 方法。
    # - return a Request object: stops process_exception() chain 将请求返回到schdular的调度队列中供以后重新访问
    pass def spider_opened(self, spider):
    spider.logger.info("Spider opened: %s" % spider.name)
  • DownloaderMiddleware中抛弃请求写法

    • 适用场景:请求异常,换代理或者换cookie等操作
    # from scrapy.exceptions import IgnoreRequest
    # raise IgnoreRequest(f'Failed to retrieve {request.url} after {max_retries} retries')

    例子:处理下载异常并重试请求

    import logging
    from scrapy.exceptions import IgnoreRequest class RetryExceptionMiddleware:
    def __init__(self):
    self.logger = logging.getLogger(__name__) def process_exception(self, request, exception, spider):
    # 记录异常信息
    self.logger.warning(f'Exception {exception} occurred while processing {request.url}') # 检查是否达到重试次数限制
    max_retries = 3
    retries = request.meta.get('retry_times', 0) + 1 if retries <= max_retries:
    self.logger.info(f'Retrying {request.url} (retry {retries}/{max_retries})')
    # 增加重试次数
    request.meta['retry_times'] = retries
    return request
    else:
    self.logger.error(f'Failed to retrieve {request.url} after {max_retries} retries')
    raise IgnoreRequest(f'Failed to retrieve {request.url} after {max_retries} retries')

    例子:切换代理

    import random
    
    class SwitchProxyMiddleware:
    def __init__(self, proxy_list):
    self.proxy_list = proxy_list
    self.logger = logging.getLogger(__name__) @classmethod
    def from_crawler(cls, crawler):
    proxy_list = crawler.settings.get('PROXY_LIST')
    return cls(proxy_list) def process_exception(self, request, exception, spider):
    self.logger.warning(f'Exception {exception} occurred while processing {request.url}') # 切换代理
    proxy = random.choice(self.proxy_list)
    self.logger.info(f'Switching proxy to {proxy}')
    request.meta['proxy'] = proxy # 重试请求
    return request
  • piplines中抛弃item写法

    • 适用场景:数据清洗、去重、验证等操作
    # from scrapy.exceptions import DropItem
    # raise DropItem("Duplicate item found: %s" % item)
  • 保存到文件(通过命令)

    from scrapy.cmdline import execute
    execute(['scrapy', 'crawl', 'centoschina_cn', '-o', 'questions.csv'])

更多精致内容:

"揭秘CentosChina爬虫项目:掌握Scrapy框架的必备技巧与数据库设计"的更多相关文章

  1. 第三百三十一节,web爬虫讲解2—Scrapy框架爬虫—Scrapy安装—Scrapy指令

    第三百三十一节,web爬虫讲解2—Scrapy框架爬虫—Scrapy安装—Scrapy指令 Scrapy框架安装 1.首先,终端执行命令升级pip: python -m pip install --u ...

  2. 关于Scrapy爬虫项目运行和调试的小技巧(下篇)

    前几天给大家分享了关于Scrapy爬虫项目运行和调试的小技巧上篇,没来得及上车的小伙伴可以戳超链接看一下.今天小编继续沿着上篇的思路往下延伸,给大家分享更为实用的Scrapy项目调试技巧. 三.设置网 ...

  3. 第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码

    第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码 打码接口文件 # -*- coding: cp936 -*- import sys import os ...

  4. 第三百三十四节,web爬虫讲解2—Scrapy框架爬虫—Scrapy爬取百度新闻,爬取Ajax动态生成的信息

    第三百三十四节,web爬虫讲解2—Scrapy框架爬虫—Scrapy爬取百度新闻,爬取Ajax动态生成的信息 crapy爬取百度新闻,爬取Ajax动态生成的信息,抓取百度新闻首页的新闻rul地址 有多 ...

  5. 第三百三十三节,web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录—获取Scrapy框架Cookies

    第三百三十三节,web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录 模拟浏览器登录 start_requests()方法,可以返回一个请求给爬虫的起始网站,这个返回的请求相当于star ...

  6. 第三百三十二节,web爬虫讲解2—Scrapy框架爬虫—Scrapy使用

    第三百三十二节,web爬虫讲解2—Scrapy框架爬虫—Scrapy使用 xpath表达式 //x 表示向下查找n层指定标签,如://div 表示查找所有div标签 /x 表示向下查找一层指定的标签 ...

  7. Python爬虫进阶之Scrapy框架安装配置

    Python爬虫进阶之Scrapy框架安装配置 初级的爬虫我们利用urllib和urllib2库以及正则表达式就可以完成了,不过还有更加强大的工具,爬虫框架Scrapy,这安装过程也是煞费苦心哪,在此 ...

  8. python爬虫入门(六) Scrapy框架之原理介绍

    Scrapy框架 Scrapy简介 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬 ...

  9. 爬虫基础(五)-----scrapy框架简介

    ---------------------------------------------------摆脱穷人思维 <五> :拓展自己的视野,适当做一些眼前''无用''的事情,防止进入只关 ...

  10. 爬虫(二)之scrapy框架

    01-scrapy介绍 02-项目的目录结构: scrapy.cfg 项目的主配置信息.(真正爬虫相关的配置信息在settings.py 文件中) items.py 设置数据存储模板,用于结构化数据, ...

随机推荐

  1. Linux中的环境变量PS1,打造你的专属终端

    文章目录 介绍 PS1的格式 设置字体样式 举例 小建议 进阶 介绍 好看的终端是怎么做的呢?通过PS1这个环境变量! PS1的格式 PS1='[\u@\h \w]\$ ' 样式: 解释: [是普通字 ...

  2. python调用微信JS_SDK及使用redis缓存access_token 和jsapi_ticket

    from flask import Flask, make_response,request import json import string import hashlib import rando ...

  3. selenium的各种操作

    import time from selenium.webdriver import Edge from selenium.webdriver.common.by import By from sel ...

  4. 阿里云Centos7 安装mysql5.7 报错:./mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: No such file or directory

    在阿里云服务器Centos7中安装mysql5.7,解压数据库初始化后,报错 ./mysqld: error while loading shared libraries: libaio.so.1: ...

  5. CF-957(D-E)

    CF-957 赛时A去写全排列--前三题我的写法都挺丑的,后面改进了再更-- Problem - D - Codeforces 虽然是很简单很经典的线性dp,但也是我第一次自己把这种题写出来ヾ(≧▽≦ ...

  6. SwiftUI学习01-基本使用

    SwiftUI 是苹果推出的一种现代化方式,用于创建跨所有 Apple 平台的用户界面.它通过声明性语法简化了 UI 的开发流程.下面是一个基本的 SwiftUI 示例,展示了如何使用 SwiftUI ...

  7. 怎么用git命令将其他分支的提交记录提取到当前分支上

    您可以使用 Git 命令 "cherry-pick" 将其他分支的提交记录提取到当前分支上.以下是使用 cherry-pick 命令的步骤:1. 切换到当前分支: `git che ...

  8. django 计算两个TimeField的时差

    在 Django 中,你可以使用 datetime 模块来计算两个 TimeField 字段的时间差.以下是一个示例: from datetime import datetime, timedelta ...

  9. JavaScript小技巧~this的保存

    在JavaScript中如果一个函数返回一个函数,此时this容易丢失,为了不使this丢失,需要在函数内部保存this. change() { let _this=this return funct ...

  10. C语言指针知识总结

    指针 定义 指针是一个变量,存储另一个变量的内存地址,它允许直接访问和操作内存中的数据,使得程序能够以更灵活和高效的方式处理数据和内存. 获取变量地址:使用取地址符 &. 访问地址上的数据:使 ...