scrapy-redis使用以及剖析(转)
scrapy-redis是一个基于redis的scrapy组件,通过它可以快速实现简单分布式爬虫程序,该组件本质上提供了三大功能:
- scheduler - 调度器
- dupefilter - URL去重规则(被调度器使用)
- pipeline - 数据持久化
scrapy-redis组件
1. URL去重
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
定义去重规则(被调度器调用并应用) a. 内部会使用以下配置进行连接Redis # REDIS_HOST = 'localhost' # 主机名 # REDIS_PORT = 6379 # 端口 # REDIS_URL = 'redis://user:pass@hostname:9001' # 连接URL(优先于以上配置) # REDIS_PARAMS = {} # Redis连接参数 默认:REDIS_PARAMS = {'socket_timeout': 30,'socket_connect_timeout': 30,'retry_on_timeout': True,'encoding': REDIS_ENCODING,}) # REDIS_PARAMS['redis_cls'] = 'myproject.RedisClient' # 指定连接Redis的Python模块 默认:redis.StrictRedis # REDIS_ENCODING = "utf-8" # redis编码类型 默认:'utf-8' b. 去重规则通过redis的集合完成,集合的Key为: key = defaults.DUPEFILTER_KEY % { 'timestamp' : int (time.time())} 默认配置: DUPEFILTER_KEY = 'dupefilter:%(timestamp)s' c. 去重规则中将url转换成唯一标示,然后在redis中检查是否已经在集合中存在 from scrapy.utils import request from scrapy.http import Request req = Request(url = 'http://www.cnblogs.com/wupeiqi.html' ) result = request.request_fingerprint(req) print (result) # 8ea4fd67887449313ccc12e5b6b92510cc53675c PS: - URL参数位置不同时,计算结果一致; - 默认请求头不在计算范围,include_headers可以设置指定请求头 示例: from scrapy.utils import request from scrapy.http import Request req = Request(url = 'http://www.baidu.com?name=8&id=1' ,callback = lambda x: print (x),cookies = { 'k1' : 'vvvvv' }) result = request.request_fingerprint(req,include_headers = [ 'cookies' ,]) print (result) req = Request(url = 'http://www.baidu.com?id=1&name=8' ,callback = lambda x: print (x),cookies = { 'k1' : 666 }) result = request.request_fingerprint(req,include_headers = [ 'cookies' ,]) print (result) """ # Ensure all spiders share same duplicates filter through redis. # DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" |
2. 调度器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
""" 调度器,调度器使用PriorityQueue(有序集合)、FifoQueue(列表)、LifoQueue(列表)进行保存请求,并且使用RFPDupeFilter对URL去重 a. 调度器 SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue' # 默认使用优先级队列(默认),其他:PriorityQueue(有序集合),FifoQueue(列表)、LifoQueue(列表) SCHEDULER_QUEUE_KEY = '%(spider)s:requests' # 调度器中请求存放在redis中的key SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat" # 对保存到redis中的数据进行序列化,默认使用pickle SCHEDULER_PERSIST = True # 是否在关闭时候保留原来的调度器和去重记录,True=保留,False=清空 SCHEDULER_FLUSH_ON_START = True # 是否在开始之前清空 调度器和去重记录,True=清空,False=不清空 SCHEDULER_IDLE_BEFORE_CLOSE = 10 # 去调度器中获取数据时,如果为空,最多等待时间(最后没数据,未获取到)。 SCHEDULER_DUPEFILTER_KEY = '%(spider)s:dupefilter' # 去重规则,在redis中保存时对应的key SCHEDULER_DUPEFILTER_CLASS = 'scrapy_redis.dupefilter.RFPDupeFilter'# 去重规则对应处理的类 """ # Enables scheduling storing requests queue in redis. SCHEDULER = "scrapy_redis.scheduler.Scheduler" # Default requests serializer is pickle, but it can be changed to any module # with loads and dumps functions. Note that pickle is not compatible between # python versions. # Caveat: In python 3.x, the serializer must return strings keys and support # bytes as values. Because of this reason the json or msgpack module will not # work by default. In python 2.x there is no such issue and you can use # 'json' or 'msgpack' as serializers. # SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat" # Don't cleanup redis queues, allows to pause/resume crawls. # SCHEDULER_PERSIST = True # Schedule requests using a priority queue. (default) # SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue' # Alternative queues. # SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.FifoQueue' # SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.LifoQueue' # Max idle time to prevent the spider from being closed when distributed crawling. # This only works if queue class is SpiderQueue or SpiderStack, # and may also block the same time when your spider start at the first time (because the queue is empty). # SCHEDULER_IDLE_BEFORE_CLOSE = 10 |
3. 数据持久化
1
2
3
4
5
6
7
8
|
2. 定义持久化,爬虫 yield Item对象时执行RedisPipeline a. 将item持久化到redis时,指定key和序列化函数 REDIS_ITEMS_KEY = '%(spider)s:items' REDIS_ITEMS_SERIALIZER = 'json.dumps' b. 使用列表保存item数据 |
4. 起始URL相关
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
""" 起始URL相关 a. 获取起始URL时,去集合中获取还是去列表中获取?True,集合;False,列表 REDIS_START_URLS_AS_SET = False # 获取起始URL时,如果为True,则使用self.server.spop;如果为False,则使用self.server.lpop b. 编写爬虫时,起始URL从redis的Key中获取 REDIS_START_URLS_KEY = '%(name)s:start_urls' """ # If True, it uses redis' ``spop`` operation. This could be useful if you # want to avoid duplicates in your start urls list. In this cases, urls must # be added via ``sadd`` command or you will get a type error from redis. # REDIS_START_URLS_AS_SET = False # Default start urls key for RedisSpider and RedisCrawlSpider. # REDIS_START_URLS_KEY = '%(name)s:start_urls' |
scrapy-redis示例
# DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
#
#
# from scrapy_redis.scheduler import Scheduler
# from scrapy_redis.queue import PriorityQueue
# SCHEDULER = "scrapy_redis.scheduler.Scheduler"
# SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue' # 默认使用优先级队列(默认),其他:PriorityQueue(有序集合),FifoQueue(列表)、LifoQueue(列表)
# SCHEDULER_QUEUE_KEY = '%(spider)s:requests' # 调度器中请求存放在redis中的key
# SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat" # 对保存到redis中的数据进行序列化,默认使用pickle
# SCHEDULER_PERSIST = True # 是否在关闭时候保留原来的调度器和去重记录,True=保留,False=清空
# SCHEDULER_FLUSH_ON_START = False # 是否在开始之前清空 调度器和去重记录,True=清空,False=不清空
# SCHEDULER_IDLE_BEFORE_CLOSE = 10 # 去调度器中获取数据时,如果为空,最多等待时间(最后没数据,未获取到)。
# SCHEDULER_DUPEFILTER_KEY = '%(spider)s:dupefilter' # 去重规则,在redis中保存时对应的key
# SCHEDULER_DUPEFILTER_CLASS = 'scrapy_redis.dupefilter.RFPDupeFilter'# 去重规则对应处理的类
#
#
#
# REDIS_HOST = '10.211.55.13' # 主机名
# REDIS_PORT = 6379 # 端口
# # REDIS_URL = 'redis://user:pass@hostname:9001' # 连接URL(优先于以上配置)
# # REDIS_PARAMS = {} # Redis连接参数 默认:REDIS_PARAMS = {'socket_timeout': 30,'socket_connect_timeout': 30,'retry_on_timeout': True,'encoding': REDIS_ENCODING,})
# # REDIS_PARAMS['redis_cls'] = 'myproject.RedisClient' # 指定连接Redis的Python模块 默认:redis.StrictRedis
# REDIS_ENCODING = "utf-8" # redis编码类型 默认:'utf-8' 配置文件
import scrapy class ChoutiSpider(scrapy.Spider):
name = "chouti"
allowed_domains = ["chouti.com"]
start_urls = (
'http://www.chouti.com/',
) def parse(self, response):
for i in range(0,10):
yield
爬虫文件
转自:https://www.cnblogs.com/wupeiqi/articles/6912807.html
scrapy-redis使用以及剖析(转)的更多相关文章
- Redis源码剖析
Redis源码剖析和注释(一)---链表结构 Redis源码剖析和注释(二)--- 简单动态字符串 Redis源码剖析和注释(三)--- Redis 字典结构 Redis源码剖析和注释(四)--- 跳 ...
- 基于Python,scrapy,redis的分布式爬虫实现框架
原文 http://www.xgezhang.com/python_scrapy_redis_crawler.html 爬虫技术,无论是在学术领域,还是在工程领域,都扮演者非常重要的角色.相比于其他 ...
- Redis源码剖析--源码结构解析
请持续关注我的个人博客:https://zcheng.ren 找工作那会儿,看了黄建宏老师的<Redis设计与实现>,对redis的部分实现有了一个简明的认识.在面试过程中,redis确实 ...
- Redis源码剖析和注释(七)--- 快速列表(quicklist)
Redis 快速列表(quicklist)1. 介绍quicklist结构是在redis 3.2版本中新加的数据结构,用在列表的底层实现. 通过列表键查看一下:redis 列表键命令详解 127.0. ...
- Scrapy爬虫及案例剖析
由于互联网的极速发展,所有现在的信息处于大量堆积的状态,我们既要向外界获取大量数据,又要在大量数据中过滤无用的数据.针对我们有益的数据需要我们进行指定抓取,从而出现了现在的爬虫技术,通过爬虫技术我们可 ...
- Scrapy+redis实现分布式爬虫
概述 什么是分布式爬虫 需要搭建一个由n台电脑组成的机群,然后在每一台电脑中执行同一组程序,让其对同一网络资源进行联合且分布的数据爬取. 原生Scrapy无法实现分布式的原因 原生Scrapy中调度器 ...
- Redis分布式缓存剖析及大厂面试精髓v6.2.6
概述 官方说明 Redis官网 https://redis.io/ 最新版本6.2.6 Redis中文官网 http://www.redis.cn/ 不过中文官网的同步更新维护相对要滞后不少时间,但对 ...
- Redis主从复制深入剖析
Redis是一个开源的,遵守BSD许可协议的key/value缓存系统,并由其高效的响应速度以及丰富的数据结构而闻名.Redis在京东的使用也是非常普遍的,包括很多关键业务上的 使用,由于Redis官 ...
- scrapy+redis去重实现增量抓取
class ProjectnameDownloaderMiddleware(object): # Not all methods need to be defined. If a method is ...
- Redis源码剖析--列表t_list实现
Redis中的列表对象比较特殊,在版本3.2之前,列表底层的编码是 ziplist 和 linkedlist 实现的, 但是在版本3.2之后,重新引入了一个 quicklist 的数据结构,列表的底层 ...
随机推荐
- 渗透利器-BadUSB 控制外网主机详解 Teensy2.0++
准备工作 一块 Teensy2.0++ 的板子(淘宝一搜就有) Arduino编译器 1.8.7版本下载连接:arduino下载地址 Teensy插件 下载连接:Teensy下载地址 [外链图片转存失 ...
- Spring常见的两种增强方式
一.编程式增强 不借助spring的配置,通过自己实例化对象来实现的增强方式 创建增强类,需要实现你需要的增强接口,(只有实现了该接口,这个类就是一个通知)) /** * 增强类 */ public ...
- numpy中的ndarray与pandas中的series、dataframe的转换
一个ndarray是一个多维同类数据容器.每一个数组有一个dtype属性,用来描述数组的数据类型. Series是一种一维数组型对象,包含了一个值序列,并且包含了数据标签----索引(index). ...
- LeetCode Day 12
LeetCode0024 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表. 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. 示例: 给定 1->2->3-> ...
- JQ主页图片划动切换效果
.wrapper { width: 726px; float: left; } #jiao_dian { width: 980px; *height: 292px; margin-top: 10px; ...
- 林轩田机器学习基石笔记1—The Learning Problem
机器学习分为四步: When Can Machine Learn? Why Can Machine Learn? How Can Machine Learn? How Can Machine Lear ...
- VRRP笔记三:配置keepalived为实现haproxy高可用的双主模型配置文件示例:
说明:其基本实现思想为创建两个虚拟路由器,并以两个节点互为主从. ! Configuration File for keepalived global_defs { notification_emai ...
- 吴裕雄--天生自然 R语言开发学习:时间序列
#-----------------------------------------# # R in Action (2nd ed): Chapter 15 # # Time series # # r ...
- 奇异值分解原理及Python实例
奇异值分解 SVD(Singular Value Decomposition)是一种重要的矩阵分解方法,可以看做是特征分解在任意矩阵上的推广,SVD是在机器学习领域广泛应用的算法. 特征值和特征向量 ...
- 从谷歌到脸书:为何巨头纷纷“钟情于”VR相机?
VR的火爆,自然无需多言.而基于VR这一个概念,已经在多个相关行业不断衍生出新的产品.服务或内容.VR眼镜.VR头盔.VR相机.VR游戏.VR影视.VR应用--但VR产业的发展并不是齐头并进,而是出现 ...