"揭秘CentosChina爬虫项目:掌握Scrapy框架的必备技巧与数据库设计"
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 requestpiplines中抛弃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框架的必备技巧与数据库设计"的更多相关文章
- 第三百三十一节,web爬虫讲解2—Scrapy框架爬虫—Scrapy安装—Scrapy指令
第三百三十一节,web爬虫讲解2—Scrapy框架爬虫—Scrapy安装—Scrapy指令 Scrapy框架安装 1.首先,终端执行命令升级pip: python -m pip install --u ...
- 关于Scrapy爬虫项目运行和调试的小技巧(下篇)
前几天给大家分享了关于Scrapy爬虫项目运行和调试的小技巧上篇,没来得及上车的小伙伴可以戳超链接看一下.今天小编继续沿着上篇的思路往下延伸,给大家分享更为实用的Scrapy项目调试技巧. 三.设置网 ...
- 第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码
第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码 打码接口文件 # -*- coding: cp936 -*- import sys import os ...
- 第三百三十四节,web爬虫讲解2—Scrapy框架爬虫—Scrapy爬取百度新闻,爬取Ajax动态生成的信息
第三百三十四节,web爬虫讲解2—Scrapy框架爬虫—Scrapy爬取百度新闻,爬取Ajax动态生成的信息 crapy爬取百度新闻,爬取Ajax动态生成的信息,抓取百度新闻首页的新闻rul地址 有多 ...
- 第三百三十三节,web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录—获取Scrapy框架Cookies
第三百三十三节,web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录 模拟浏览器登录 start_requests()方法,可以返回一个请求给爬虫的起始网站,这个返回的请求相当于star ...
- 第三百三十二节,web爬虫讲解2—Scrapy框架爬虫—Scrapy使用
第三百三十二节,web爬虫讲解2—Scrapy框架爬虫—Scrapy使用 xpath表达式 //x 表示向下查找n层指定标签,如://div 表示查找所有div标签 /x 表示向下查找一层指定的标签 ...
- Python爬虫进阶之Scrapy框架安装配置
Python爬虫进阶之Scrapy框架安装配置 初级的爬虫我们利用urllib和urllib2库以及正则表达式就可以完成了,不过还有更加强大的工具,爬虫框架Scrapy,这安装过程也是煞费苦心哪,在此 ...
- python爬虫入门(六) Scrapy框架之原理介绍
Scrapy框架 Scrapy简介 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬 ...
- 爬虫基础(五)-----scrapy框架简介
---------------------------------------------------摆脱穷人思维 <五> :拓展自己的视野,适当做一些眼前''无用''的事情,防止进入只关 ...
- 爬虫(二)之scrapy框架
01-scrapy介绍 02-项目的目录结构: scrapy.cfg 项目的主配置信息.(真正爬虫相关的配置信息在settings.py 文件中) items.py 设置数据存储模板,用于结构化数据, ...
随机推荐
- 安装PHP5.6.20
安装php的前提是安装了数据库和httpd!!!!!!!! 1 因为yum缺省安装的是PHP5.4,所以先要添加yum库 [root@svnhost ~]# rpm -Uvh https://mirr ...
- Python中r+,w+,a+的区别
相信有很多人对他们的区别不清楚,网上对他们的讨论又过于复杂. 其实利用光标位置来区分它们就会变得非常地简单. r+读写模式 打开文件之后光标位置位于0的位置 根据光标位置读写 w+写读模式 会清空文件 ...
- Java面试知识点(六)hashmap深度理解
1.hashmap 的数据结构 要知道 hashmap 是什么,首先要搞清楚它的数据结构,在 java 编程语言中,最基本的结构就是两种,一个是数组,另外一个是模拟指针(引用),所有的数据结构都可以用 ...
- 使用Redis+SpringBoot实现定时任务测试
Redis实现定时任务是基于对RedisKey值的监控 具体代码实现: 代码GitHub地址:https://github.com/Tom-shushu/Project 建一个SpringBoot项目 ...
- 实验9.单臂路由实现Vlan互通实验
# 单臂路由实现Vlan互通实验 本实验用于测试单臂路由方式实现Vlan路由. 实验组 实验过程 SW int g0/0/1 port link-type access port default vl ...
- NXP i.MX 8M Mini工业核心板硬件说明书(四核ARM Cortex-A53 + 单核ARM Cortex-M4,主频1.6GHz)
1 硬件资源 创龙科技SOM-TLIMX8是一款基于NXP i.MX 8M Mini的四核ARM Cortex-A53 + 单核ARM Cortex-M4异构多核处理器设计的高端工业 ...
- Odoo17.0 基于企业微信的备用金和费用报销
前面讲过了企业微信的基础应用,现在我们来看一下如何借助企业微信的审批端能力结合odoo来实现企业中的两大常规业务流程备用金和费用报销. 企业微信端设置 我们这里使用的是企业微信的原生审批流程,因此我们 ...
- 面试官:Dubbo一次RPC请求经历哪些环节?
大家好,我是三友~~ 今天继续探秘系列,扒一扒一次RPC请求在Dubbo中经历的核心流程. 本文是基于Dubbo3.x版本进行讲解 一个简单的Demo 这里还是老样子,为了保证文章的完整性和连贯性,方 ...
- ComfyUI进阶:Comfyroll插件 (五)
ComfyUI进阶:Comfyroll插件 (五) 前言: 学习ComfyUI是一场持久战,而Comfyroll 是一款功能强大的自定义节点集合,专为 ComfyUI 用户打造,旨在提供更加丰富和专业 ...
- Django 用户认证系统使用总结
Django用户认证系统使用总结 by:授客 QQ:1033553122 测试环境 Win7 Django 1.11 使用Django认证系统 本文按默认配置讲解Django认证系统的用法.如果默 ...