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 ...
随机推荐
- Java获取网络IP
Java获取获取网络IP,浅尝辄止咯- import java.net.InetAddress; import java.net.UnknownHostException; /** * 获取网络IP ...
- iOS多线程与网络开发之NSOperation
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 游戏官方下 ...
- 转载:IE下div使用margin:0px auto不居中的原因
转自:http://www.blogjava.net/sealyu/archive/2010/01/08/308640.html 一般在将div居中显示时,使用css: divX {margin:0 ...
- linux下常用FTP命令 1. 连接ftp服务器
1. 连接ftp服务器 格式:ftp [hostname| ip-address] a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密 ...
- jquery中判断选择器,找没找到元素用$().size()==0
jquery中判断选择器,找没找到元素用$().size()==0
- iOS 使用AFNetworking 设置cookie
本问题是由于多账号访问统一服务器时, 由于服务器那边接收到sessionid一样, 故无法区分账号信息. 所以需要在移动端请求的时候重新设置cookie, 步骤如下: 1. 在登录的时候, 先将 re ...
- RAC DBCA 找不到共享磁盘
(一) 前言: 通过vmware workstation 走iscsi协议.安装RAC 集群架构,DBCA 时不能识别ASM 共享存储(按理来说这一版都是权限的问题).同一时候,本想通过RMAN ...
- Kafka学习之一深度解析
背景介绍 Kafka简介 Kafka是一种分布式的,基于发布/订阅的消息系统.主要设计目标如下: 以时间复杂度为O(1)的方式提供消息持久化能力,即使对TB级以上数据也能保证常数时间的访问性能 高吞吐 ...
- Unity 如何高效的解析数据
昨天和朋友聊天时,他遇到这么一个问题:现在有按照一定格式的数据,例如:#code==text 此处是注释100==确定101==取消key==value 这么个格式的,说白了就是怎样解析这些固定格式字 ...
- when an event of selector will be fired
OP_READ Operation-set bit for read operations. Suppose that a selection key's interest set contains ...