scrapy+redis组件

scrapy-redis插件:实现分布式爬虫。

  • scheduler - 调度器
  • dupefilter - URL去重规则(被调度器使用)
  • pipeline   - 数据持久化

pip3 install scrapy-redis

一,url去重

定义去重规则(被调度器调用并应用)

    a. 内部会使用以下配置进行连接Redis

        # REDIS_HOST = ‘localhost‘                            # 主机名
        # REDIS_PORT = 6379                                   # 端口
        # REDIS_URL = ‘redis://user:[email protected]: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.

 二,调度器

"""
调度器,调度器使用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  

三,数据持久化

2. 定义持久化,爬虫yield Item对象时执行RedisPipeline

    a. 将item持久化到redis时,指定key和序列化函数

        REDIS_ITEMS_KEY = ‘%(spider)s:items‘
        REDIS_ITEMS_SERIALIZER = ‘json.dumps‘

    b. 使用列表保存item数据

四,起始url

"""
起始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‘

五,eg

# 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:[email protected]: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/catherine007/p/8678718.html

时间: 2024-08-10 08:00:12

scrapy+redis组件的相关文章

Node.js与Sails~redis组件的使用

有段时间没写关于NodeJs的文章了,今天也是为了解决高并发的问题,而想起了这个东西,IIS的站点在并发量达到200时有了一个瓶颈,于是想到了这个对高并发支持比较好的框架,nodeJs在我之前写出一些文章,主要为sails框架为主,介绍了一些使用方法,今天主要说下redis组件! 项目:SailsMvc 开发工具:webstorm 语言:nodejs 框架:sails 包:redis 主要介绍几个用法,为string,set,hash和list的使用 测试redis组件的代码 index: fu

Apache Camel系列(3)----Redis组件

Redis组件允许你从Redis接收消息,以及将消息发送给Redis.RedisProducer的功能很强大,几乎能执行所有的Redis Command,这些Command都是在Message的header中进行设置的.遗憾的是RedisConsumer仅仅支持pub/sub模式,不支持Point2Point,这意味这在Camel中,通过阻塞的方式消费Lists中的消息是不可行的.我反馈了这个问题到Apache Camel Mail List,希望以后的版本支持P2P更能.下面演示如何使用cam

新生命Redis组件(.Net Core 开源)

NewLife.Redis 是一个Redis客户端组件,以高性能处理大数据实时计算为目标.Redis协议基础实现Redis/RedisClient位于X组件,本库为扩展实现,主要增加列表结构.哈希结构.队列等高级功能. 源码: https://github.com/NewLifeX/NewLife.RedisNuget:NewLife.Redis 特性 在ZTO大数据实时计算广泛应用,200多个Redis实例稳定工作一年多,每天处理近1亿包裹数据,日均调用量80亿次 低延迟,Get/Set操作平

【分布式架构】(10)---基于Redis组件的特性,实现一个分布式限流

分布式---基于Redis进行接口IP限流 场景 为了防止我们的接口被人恶意访问,比如有人通过JMeter工具频繁访问我们的接口,导致接口响应变慢甚至崩溃,所以我们需要对一些特定的接口进行IP限流,即一定时间内同一IP访问的次数是有限的. 实现原理 用Redis作为限流组件的核心的原理,将用户的IP地址当Key,一段时间内访问次数为value,同时设置该Key过期时间. 比如某接口设置相同IP10秒内请求5次,超过5次不让访问该接口. 1. 第一次该IP地址存入redis的时候,key值为IP地

redis组件介绍

redis-server:服务器端工具 redis-cli:客户端工具 redis-benchmark:redis性能压力测试工具 redis-check-dump(rdb格式) & redis-check-aof(aof格式):检测持久化存储RDB/AOF的文件格式是否错误,以及发现错误进行修复 redis-shutdown:用于关闭redis redis-sentinel:用于实现redis主从切换的工具

淘搜索之网页抓取系统分析与实现(2)—redis + scrapy

1.scrapy+redis使用 (1)应用 这里redis与scrapy一起,scrapy作为crawler,而redis作为scrapy的调度器.如架构图中的②所示.图1 架构图 (2)为什么选择redis redis作为调度器的实现仍然和其特性相关,可见<一淘搜索之网页抓取系统分析与实现(1)--redis使用>(http://blog.csdn.net/u012150179/article/details/38226711)中关于redis的分析. 2.redis实现scrapy sc

Redis与Scrapy

Redis与Scrapy Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs. --Redis Home Page 1

scrapy 中 settings.py 中字段的意思

# -*- coding: utf-8 -*- # Scrapy settings for fenbushi 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/topi

爬虫系列之Scrapy框架

一 scrapy框架简介 1 介绍 (1) 什么是Scrapy? Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,非常出名,非常强悍.所谓的框架就是一个已经被集成了各种功能(高性能异步下载,队列,分布式,解析,持久化等)的具有很强通用性的项目模板.对于框架的学习,重点是要学习其框架的特性.各个功能的用法即可. Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速.简单.可扩展的方式从网站中提取所需的数据.但目前Scra