scrapy爬虫系列之七--scrapy_redis的使用
功能点:如何发送携带cookie访问登录后的页面,如何发送post请求登录
简单介绍:
- 安装:pip3 install scrapy_redis
- 在scrapy的基础上实现了更多的功能:如request去重(增量爬虫),爬虫持久化,实现分布式
- 工作流程:通过redis实现调度器的队列和指纹集合;每个request生成一个指纹,在存入redis之前,首先判断这个指纹是否已经存在,如果不存在则存入。
- 配置:
# 确保所有的爬虫通过Redis去重
DUPEFILTER_CLASS = 'scrapy_redis.dupefilter.RFPDupeFilter'
# 启用Redis调度存储请求队列
SCHEDULER = 'scrapy_redis.scheduler.Scheduler'
# 不清除Redis队列、这样可以暂停/恢复 爬取
SCHEDULER_PERSIST = True
# 保存item到redis
ITEM_PIPELINES = {
'scrapy_redis.pipelines.RedisPipeline': 400
}
# reids服务器地址
REDIS_URL = 'redis://192.168.3.20:6379'
- redis中访问:
keys *里有3个键
爬虫名:requests Scheduler队列,存放待请求的request对象,获取的过程是pop操作,即获取一个会去除一个
爬虫名:dupefilter 指纹集合,存放的是已经进入scheduler队列的request对象的指纹,指纹默认由请求方法、url和请求体组成
爬虫名:items 存放的是获取到的item信息,在 pipeline中 开启才会存入。
- request对象什么时候入队?
1、dont_filter=True,构造请求的时候,把dont_filter设置为True,该url会被反复抓取(url地址对应的内容会更新的情况,类似百度贴吧)
2、一个全新的url地址被抓到的时候,构造request请求
3、url地址在start_urls中的时候,会入队,不管之前是否请求过(原因:构造start_url地址的请求的时候,dont_filter=True)
4、代码,scheduler.py的enqueue_request方法:def enqueue_request(self, request):
if not request.dont_filter and self.df.request_seen(request):
self.df.log(request, self.spider)
return False
self.queue.push(request)
return True
- scrapy_redis的去重方法
使用sha1加密request得到指纹
把指纹存到redis的集合中
下次新来的request,同样的方式生成指纹,判断指纹是否存在redis的集合中
- 生成指纹
fp = hashlib.sha1()
fp.update(to_bytes(request.method))
fp.update(to_bytes(canonicalize_url(request.url)))
fp.update(request.body or b'')
return fp.hexdigest()
- 判断数据是否存在redis的集合中,不存在则插入
dupefilter.py的request_seen方法
added = self.server.sadd(self.key, fp)
return added == 0
- 在引入scrapy_redis之前,scrapy是怎么去重的?
scrapy.dupefilters.py的 RFPDupeFilter,request_seen方法:
# 首先也会生成一个指纹,判断是否在集合中,如果存在,说明已经抓取过
# requests.seen文件
def request_seen(self, request):
fp = self.request_fingerprint(request)
if fp in self.fingerprints:
return True
self.fingerprints.add(fp)
if self.file:
self.file.write(fp + os.linesep)
爬取网站:dmoz
完整代码:https://files.cnblogs.com/files/bookwed/dmoztools.zip
主要代码:
dmoz.py
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class DmozSpider(CrawlSpider):
name = 'dmoz'
allowed_domains = ['dmoztools.net']
start_urls = ['http://www.dmoztools.net'] rules = (
Rule(LinkExtractor(
restrict_css=('.top-cat', '.sub-cat', 'cat-item')
), callback='parse_item', follow=True),
) def parse_item(self, response):
for div in response.css(".title-and-desc"):
yield {
'name': div.css(".site-title::text").extract_first(),
'desc': div.css(".site-descr::text").extract_first().strip(),
'link': div.css("a::attr(href)").extract_first(),
}
settings.py
# -*- coding: utf-8 -*- # Scrapy settings for dmoztools project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'dmoztools' SPIDER_MODULES = ['dmoztools.spiders']
NEWSPIDER_MODULE = 'dmoztools.spiders' # 确保所有的爬虫通过Redis去重
DUPEFILTER_CLASS = 'scrapy_redis.dupefilter.RFPDupeFilter'
# 启用Redis调度存储请求队列
SCHEDULER = 'scrapy_redis.scheduler.Scheduler'
# 不清除Redis队列、这样可以暂停/恢复 爬取;队列中的内容是否持久化
SCHEDULER_PERSIST = True
# 使用优先级调度请求队列 (默认使用)
# SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue'
# 可选用的其它队列
# SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.FifoQueue'
# SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.LifoQueue'
# 最大空闲时间防止分布式爬虫因为等待而关闭
# SCHEDULER_IDLE_BEFORE_CLOSE = 10 # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'dmoztools (+http://www.yourdomain.com)' # Obey robots.txt rules
ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default)
#COOKIES_ENABLED = False # Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False # Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#} # Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'dmoztools.middlewares.DmoztoolsSpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'dmoztools.middlewares.DmoztoolsDownloaderMiddleware': 543,
#} # Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#} # Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'dmoztools.pipelines.DmoztoolsPipeline': 300,
'scrapy_redis.pipelines.RedisPipeline': 400
} # Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' REDIS_URL = 'redis://192.168.3.20:6379'
scrapy爬虫系列之七--scrapy_redis的使用的更多相关文章
- [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...
- scrapy爬虫系列之开头--scrapy知识点
介绍:Scrapy是一个为了爬取网站数据.提取结构性数据而编写的应用框架,我们只需要实现少量的代码,就能够快速抓取.Scrapy使用了Twisted异步网络框架,可以加快我们的下载速度. 0.说明: ...
- scrapy爬虫系列之一--scrapy的基本用法
功能点:scrapy基本使用 爬取网站:传智播客老师 完整代码:https://files.cnblogs.com/files/bookwed/first.zip 主要代码: ff.py # -*- ...
- scrapy爬虫系列之二--翻页爬取及日志的基本用法
功能点:如何翻页爬取信息,如何发送请求,日志的简单实用 爬取网站:腾讯社会招聘网 完整代码:https://files.cnblogs.com/files/bookwed/tencent.zip 主要 ...
- scrapy爬虫系列之六--模拟登录
功能点:如何发送携带cookie访问登录后的页面,如何发送post请求登录 爬取网站:bilibili.github 完整代码:https://files.cnblogs.com/files/book ...
- scrapy爬虫系列之五--CrawlSpider的使用
功能点:CrawlSpider的基本使用 爬取网站:保监会 主要代码: cf.py # -*- coding: utf-8 -*- import scrapy from scrapy.linkextr ...
- scrapy爬虫系列之三--爬取图片保存到本地
功能点:如何爬取图片,并保存到本地 爬取网站:斗鱼主播 完整代码:https://files.cnblogs.com/files/bookwed/Douyu.zip 主要代码: douyu.py im ...
- scrapy爬虫系列之四--爬取列表和详情
功能点:如何爬取列表页,并根据列表页获取详情页信息? 爬取网站:东莞阳光政务网 完整代码:https://files.cnblogs.com/files/bookwed/yangguang.zip 主 ...
- scrapy爬虫学习系列五:图片的抓取和下载
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
随机推荐
- 关于解决用tutorial7教程中的代码打造一款自己的播放器中的声音噪音问题
////////////////////////////////////////////////////////////////////////////////////////////对于用FFMPE ...
- (转)sqlite3生成lib遇到的问题
今天想用一用sqlite,但是下载后发现只有DLL,没有LIB,只能自己生成了.在H:/Program Files/Microsoft Visual Studio 8/VC/bin里面有个lib.ex ...
- 配置OpenGL的开发环境
OpenGL库资源下载 http://pan.baidu.com/s/1ntVsReL 环境搭建 将下载好的文件进行解压,可以得到后缀为.h..lib..dll三类文件,对这三类文件作如下处理: 将所 ...
- asp.net mvc webconfig配置文件操作
读取web.config数据,可以不用编译.如发布后,非常有用web.config文件<configuration> <appSettings> <add key=&qu ...
- Extjs 下拉框
刚刚熟练了easyui控件的使用,又開始了如今的这个项目. 这个项目是个半成品.前端使用的是Extjs控件,jsp中没有代码.就引用了非常多的js...于是乎有种不知所措了呀. . . 说实话特别的不 ...
- c++ time_t
type struct tm <ctime> Time structure Structure containing a calendar date and time broken dow ...
- kafka学习之-深入研究原理
参考博客: http://www.cnblogs.com/fxjwind --阿里牛人 http://blog.csdn.net/lizhitao/article/details/41778193 ...
- MathType编辑半直积符号的步骤
在数学中,特别是叫做群论的抽象代数领域中,半直积(semidirect product)是从其中一个是正规子群的两个子群形成一个群的特定方法.半直积是直积的推广.半直积是作为集合的笛卡尔积,但带有特定 ...
- C语言中文件目录(一正二反)斜杠
正斜杠unix“/” linux,安卓,苹果都是 windows是两个反斜杠“\\”,但现在也兼容了可以使用正斜杠“/”
- Socket无连接简单实例
使用无连接的套接字,我们能够在自我包含的数据包里发送消息,采用独立的读函数读取消息,读取的消息是使用独立的发送函数发送的.但是UDP数据包不能保证可靠传输,存在许多的因素,比如网络繁忙等等,都有可能阻 ...