分布式爬虫Scrapy-redis框架源码解析

文章目录

    • 一、scrapy-redis架构原理
    • Scrapy-redis提供了下面四种组件(components):
    • 1. Scheduler(调度器):
    • 2. Duplication Filter(过滤工具):
    • 3. Item Pipeline(管道):
    • 4. Base Spider:
    • 二、源码解析
    • 1.connection.py
    • 2.defaults.py
    • 3. dupefilter.py
    • 4. picklecompat.py
    • 5. piplines.py
    • 6.queue.py
    • 7. scheduler.py
    • 8. spider.py
    • 9.utils.py

scrapy-redis的官方文档写的比较简洁,没有提及其运行原理,所以如果想全面的理解分布式爬虫的运行原理,还是得看scrapy-redis的源代码才行。

官方站点:https://github.com/rolando/scrapy-redis

scrapy-redis工程的主体还是是redis和scrapy两个库,工程本身实现的东西不是很多,这个工程就像胶水一样,把这两个插件粘结了起来。下面我们来看看,scrapy-redis的每一个源代码文件都实现了什么功能,最后如何实现分布式的爬虫系统。

一、scrapy-redis架构原理

分布式爬虫Scrapy-redis框架源码解析_第1张图片

Scrapy-redis提供了下面四种组件(components):

四种组件意味着这四个模块都要做相应的修改

  • Scheduler(调度器)
  • Duplication Filter(重复过滤)
  • Item Pipeline(管道)
  • Base Spider(继承类)

下面分别介绍四个组件:

1. Scheduler(调度器):

Scrapy改造了python本来的collection.deque(双向队列)形成了自己的Scrapy queue(https://github.com/scrapy/queuelib/blob/master/queuelib/queue.py)),但是Scrapy多个spider不能共享待爬取队列Scrapy queue, 即Scrapy本身不支持爬虫分布式,scrapy-redis 的解决是把这个Scrapy queue换成redis数据库(也是指redis队列),从同一个redis-server存放要爬取的request,便能让多个spider去同一个数据库里读取。

Scrapy中跟“待爬队列”直接相关的就是调度器Scheduler,它负责对新的request进行入列操作(加入Scrapy queue),取出下一个要爬取的request(从Scrapy queue中取出)等操作。它把待爬队列按照优先级建立了一个字典结构,比如:

 {
        优先级0 : 队列0
        优先级1 : 队列1
        优先级2 : 队列2
    }

然后根据request中的优先级,来决定该入哪个队列,出列时则按优先级较小的优先出列。为了管理这个比较高级的队列字典,Scheduler需要提供一系列的方法。但是原来的Scheduler已经无法使用,所以使用Scrapy-redis的scheduler组件。

2. Duplication Filter(过滤工具):

Scrapy中用集合实现这个request去重功能,Scrapy中把已经发送的request指纹放入到一个集合中,把下一个request的指纹拿到集合中比对,如果该指纹存在于集合中,说明这个request发送过了,如果没有则继续操作。这个核心的判重功能是这样实现的:

def request_seen(self, request):
        # self.request_figerprints 就是一个指纹集合  
        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)

在scrapy-redis中去重是由Duplication Filter组件来实现的,它通过redis的set 不重复的特性,巧妙的实现了Duplication Filter去重。scrapy-redis调度器从引擎接受request,将request的指纹存redis的set检查是否重复,并将不重复的request push写redis的 request queue。

引擎请求request(Spider发出的)时,调度器从redis的request queue队列里根据优先级pop 出个request 返回给引擎,引擎将此request发给spider处理。

3. Item Pipeline(管道):

引擎将(Spider返回的)爬取到的Item给Item Pipeline,scrapy-redis 的Item Pipeline将爬取到的 Item 存redis的 items queue。

修改过Item Pipeline可以很方便的根据 key 从 items queue 提取item,从而实现items processes集群。

4. Base Spider:

不在使用scrapy原有的Spider类,重写的RedisSpider继承了Spider和RedisMixin这两个类,RedisMixin是用来从redis读取url的类。

当我们生成一个Spider继承RedisSpider时,调用setup_redis函数,这个函数会去连接redis数据库,然后会设置signals(信号):

  • 一个是当spider空闲时候的signal,会调用spider_idle函数,这个函数调用schedule_next_request函数,保证spider是一直活着的状态,并且抛出DontCloseSpider异常。
  • 一个是当抓到一个item时的signal,会调用item_scraped函数,这个函数会调用schedule_next_request函数,获取下一个request。

Scrapy-redis框架执行过程总结:

  1. 最后总结一下scrapy-redis的总体思路:这套组件通过重写scheduler和 spider类,实现了调度、spider启动和redis的交互。

  2. 实现新的dupefilter和queue类,达到了判重和调度容器和redis 的交互,因为每个主机上的爬虫进程都访问同一个redis数据库,所以调度和判重都统一进行统一管理,达到了分布式爬虫的目的。

  3. 当spider被初始化时,同时会初始化一个对应的scheduler对象,这个调度器对象通过读取settings,配置好自己的调度容器queue和判重工具dupefilter。

  4. 每当一个spider产出一个request的时候,scrapy引擎会把这个reuqest递交给这个spider对应的scheduler对象进行调度,scheduler对象通过访问redis对request进行判重,如果不重复就把他添加进redis中的调度器队列里。当调度条件满足时,scheduler对象就从redis的调度器队列中取出一个request发送给spider,让他爬取。

  5. 当spider爬取的所有暂时可用url之后,scheduler发现这个spider对应的redis的调度器队列空了,于是触发信号spider_idle,spider收到这个信号之后,直接连接redis读取start_urls池,拿取新的一批url入口,然后再次重复上边的工作。

二、源码解析

下面的源码的注释基本都有,我就重要的代码进行解释

1.connection.py

这个文件是用于连接redis的文件,用到比较多,也是最重要的文件

import six

from scrapy.utils.misc import load_object

from . import defaults


# Shortcut maps 'setting name' -> 'parmater name'.
#关系
SETTINGS_PARAMS_MAP = {
    'REDIS_URL': 'url',
    'REDIS_HOST': 'host',
    'REDIS_PORT': 'port',
    'REDIS_ENCODING': 'encoding',
}

#获取一个redis连接实例
#生成连接redis的参数
def get_redis_from_settings(settings):
    """Returns a redis client instance from given Scrapy settings object.

    This function uses ``get_client`` to instantiate the client and uses
    ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You
    can override them using the ``REDIS_PARAMS`` setting.

    Parameters
    ----------
    settings : Settings
        A scrapy settings object. See the supported settings below.

    Returns
    -------
    server
        Redis client instance.

    Other Parameters
    ----------------
    REDIS_URL : str, optional
        Server connection URL.
    REDIS_HOST : str, optional
        Server host.
    REDIS_PORT : str, optional
        Server port.
    REDIS_ENCODING : str, optional
        Data encoding.
    REDIS_PARAMS : dict, optional
        Additional client parameters.
    """
    #浅拷贝 是为了防止params的改变,会导致默认SETTINGS_PARAMS被改变
    params = defaults.REDIS_PARAMS.copy()
    #将设置中的参数更新进入params中
    params.update(settings.getdict('REDIS_PARAMS'))
    # XXX: Deprecate REDIS_* settings.
    #遍历映射表,获取指定的参数
    for source, dest in SETTINGS_PARAMS_MAP.items():
        #优先使用设置中的参数
        val = settings.get(source)
        #如果设置中没有进行设置,则params不更新
        if val:
            params[dest] = val

    # Allow ``redis_cls`` to be a path to a class.
    if isinstance(params.get('redis_cls'), six.string_types):
        params['redis_cls'] = load_object(params['redis_cls'])

    return get_redis(**params)


# Backwards compatible alias.
from_settings = get_redis_from_settings


def get_redis(**kwargs):
    """Returns a redis client instance.

    Parameters
    ----------
    redis_cls : class, optional
        Defaults to ``redis.StrictRedis``.
    url : str, optional
        If given, ``redis_cls.from_url`` is used to instantiate the class.
    **kwargs
        Extra parameters to be passed to the ``redis_cls`` class.

    Returns
    -------
    server
        Redis client instance.

    """
    #没有redis_cls 则用默认的redis连接
    redis_cls = kwargs.pop('redis_cls', defaults.REDIS_CLS)
    #判断kwarg有没有url
    url = kwargs.pop('url', None)
    if url:
        return redis_cls.from_url(url, **kwargs)
    else:
        #走这里
        return redis_cls(**kwargs)

Connection提供了一个很重要的函数,from_settings = get_redis_from_settings这个函数引入defualt.py文件,定义了我们访问过的指纹。pipline,queue,schedule文件都会调用。

2.defaults.py

主要存放默认的参数

import redis


# For standalone use.
#去重的键名key
DUPEFILTER_KEY = 'dupefilter:%(timestamp)s'

#定义的存储items的键名,spiders是爬虫的名称
PIPELINE_KEY = '%(spider)s:items'
#redis连接对象,是用于连接redis
REDIS_CLS = redis.StrictRedis
#字符集编码
REDIS_ENCODING = 'utf-8'
# Sane connection defaults.
# redis的连接的参数
REDIS_PARAMS = {
    'socket_timeout': 30,
    'socket_connect_timeout': 30,
    'retry_on_timeout': True,
    'encoding': REDIS_ENCODING,
}
# 队列的变量名,用于存储爬取的url队列
SCHEDULER_QUEUE_KEY = '%(spider)s:requests'
# 优先级队列,用于规定队列的进出方式
SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue'
# 用于去重的key,给request加指纹存储的地方
SCHEDULER_DUPEFILTER_KEY = '%(spider)s:dupefilter'
# 用于生成指纹的类
SCHEDULER_DUPEFILTER_CLASS = 'scrapy_redis.dupefilter.RFPDupeFilter'
# 起始url对应的key
START_URLS_KEY = '%(name)s:start_urls'
# 起始url的类型
START_URLS_AS_SET = False

3. dupefilter.py

scrapy的去重是利用集合来实现的,而在scrapy分布式的去重就需要利用共享的集合,那么这里使用的就是redis中集合数据结构。

import logging
import time

from scrapy.dupefilters import BaseDupeFilter
from scrapy.utils.request import request_fingerprint

from . import defaults
from .connection import get_redis_from_settings


logger = logging.getLogger(__name__)


# TODO: Rename class to RedisDupeFilter.
class RFPDupeFilter(BaseDupeFilter):
    """
    Redis-based request duplicates filter.

    This class can also be used with default Scrapy's scheduler.

    """

    logger = logger

    def __init__(self, server, key, debug=False):
        """
        Initialize the duplicates filter.

        Parameters#参数
        ----------
        #server:redis的连接实例
        server : redis.StrictRedis
            The redis server instance.

        key : str
            Redis key Where to store fingerprints.  存储requests指纹的地方

        debug : bool, optional
            Whether to log filtered requests.   是否记录过滤的requests

        """
        self.server = server
        self.key = key
        self.debug = debug
        self.logdupes = True

    #类方法传递的当前方法
    @classmethod
    def from_settings(cls, settings):
        """Returns an instance from given settings.

        This uses by default the key ``dupefilter:``. When using the
        ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as
        it needs to pass the spider name in the key.

        Parameters
        ----------
        settings : scrapy.settings.Settings

        Returns
        -------
        RFPDupeFilter
            A RFPDupeFilter instance.


        """
        #获取redis的连接实例
        server = get_redis_from_settings(settings)
        # XXX: This creates one-time key. needed to support to use this
        # class as standalone dupefilter with scrapy's default scheduler
        # if scrapy passes spider on open() method this wouldn't be needed
        # TODO: Use SCRAPY_JOB env as default and fallback to timestamp.
        #生成存储指纹的key
        key = defaults.DUPEFILTER_KEY % {'timestamp': int(time.time())}
        #使用默认值Flase
        debug = settings.getbool('DUPEFILTER_DEBUG')
        #传给当前类,并把参数传给init函数
        return cls(server, key=key, debug=debug)

    @classmethod
    def from_crawler(cls, crawler):
        """Returns instance from crawler.

        Parameters
        ----------
        crawler : scrapy.crawler.Crawler

        Returns
        -------
        RFPDupeFilter
            Instance of RFPDupeFilter.

        """
        return cls.from_settings(crawler.settings)

    def request_seen(self, request):
        """Returns True if request was already seen.

        Parameters
        ----------
        request : scrapy.http.Request

        Returns
        -------
        bool

        """
        #s生成一个指纹
        fp = self.request_fingerprint(request)
        # This returns the number of values added, zero if already exists.
        #将指纹加入redis 指纹是一个集合类型
        # self.server  redis连接实例
        #self.key 是存储指纹的key  fp指纹
        #self.key 已经存在返回0,不存在则返回1
        added = self.server.sadd(self.key, fp)

        #当added为0,说明指纹已经存在,返回true。否则返回False
        return added == 0

    def request_fingerprint(self, request):
        """Returns a fingerprint for a given request.

        Parameters
        ----------
        request : scrapy.http.Request

        Returns
        -------
        str

        """
        return request_fingerprint(request)

    @classmethod
    def from_spider(cls, spider):
        settings = spider.settings
        server = get_redis_from_settings(settings)
        dupefilter_key = settings.get("SCHEDULER_DUPEFILTER_KEY", defaults.SCHEDULER_DUPEFILTER_KEY)
        key = dupefilter_key % {'spider': spider.name}
        debug = settings.getbool('DUPEFILTER_DEBUG')
        return cls(server, key=key, debug=debug)
    #当爬虫结束时,清空指纹
    def close(self, reason=''):
        """Delete data on close. Called by Scrapy's scheduler.

        Parameters
        ----------
        reason : str, optional

        """
        self.clear()

    def clear(self):
        """Clears fingerprints data."""
        self.server.delete(self.key)

    def log(self, request, spider):
        """Logs given request.

        Parameters
        ----------
        request : scrapy.http.Request
        spider : scrapy.spiders.Spider

        """
        if self.debug:
            msg = "Filtered duplicate request: %(request)s"
            self.logger.debug(msg, {'request': request}, extra={'spider': spider})
        elif self.logdupes:
            msg = ("Filtered duplicate request %(request)s"
                   " - no more duplicates will be shown"
                   " (see DUPEFILTER_DEBUG to show all duplicates)")
            self.logger.debug(msg, {'request': request}, extra={'spider': spider})
            self.logdupes = False

request_seen()方法直接换成了数据库的存储方式,鉴别重复的方式,还是使用指纹,指纹同样,是依靠request_fingerprint()方法俩获取的。获取指纹之后就直接向集合添加指纹,如果添加成功,说明这个指纹原本不存在于集合中,返回1。代码中最后的返回结果是判断添加结果是否为0,如果刚才返回为1,那么这个判定结果是false,也就是不重复,否则判定为重复。

4. picklecompat.py

这里实现了loads和dumps两个函数,其实就是实现了一个序列化器。

因为redis数据库不能存储复杂对象(key部分只能是字符串,value部分只能是字符串,字符串列表,字符串集合和hash),所以我们存啥都要先串行化成文本才行。

这里使用的就是python的pickle模块,一个兼容py2和py3的串行化工具。这个serializer主要用于一会的scheduler存reuqest对象。

"""A pickle wrapper module with protocol=-1 by default."""

try:
    import cPickle as pickle  # PY2
except ImportError:
    import pickle#PY3用的包



#反序列化就是将字符串转换为json数据
def loads(s):
    return pickle.loads(s)

#序列化就是将json数据转换为字符串
def dumps(obj):
    return pickle.dumps(obj, protocol=-1)


5. piplines.py

用于处理爬虫爬取的数据将数据序列化放到redis中

from scrapy.utils.misc import load_object
from scrapy.utils.serialize import ScrapyJSONEncoder
from twisted.internet.threads import deferToThread

from . import connection, defaults

#序列化的字符串
default_serialize = ScrapyJSONEncoder().encode


class RedisPipeline(object):
    """Pushes serialized item into a redis list/queue

    Settings
    --------
    REDIS_ITEMS_KEY : str
        Redis key where to store items.
    REDIS_ITEMS_SERIALIZER : str
        Object path to serializer function.

    """

    def __init__(self, server,
                 key=defaults.PIPELINE_KEY,
                 serialize_func=default_serialize):
        """Initialize pipeline.

        Parameters
        ----------
        server : StrictRedis
            Redis client instance.
        key : str
            Redis key where to store items.
        serialize_func : callable
            Items serializer function.

        """
        self.server = server
        self.key = key
        self.serialize = serialize_func
    #将类本身传入函数
    #用来生成参数和redis的连接实例
    @classmethod
    def from_settings(cls, settings):
        #from_settings = get_redis_from_settings
        #生成redis连接实例
        params = {
            'server': connection.from_settings(settings),
        }
        #如果设置中有item_key,我们就用设置中的
        if settings.get('REDIS_ITEMS_KEY'):
            params['key'] = settings['REDIS_ITEMS_KEY']
        #如果设置中有序列化的函数,则优先使用设置中的
        if settings.get('REDIS_ITEMS_SERIALIZER'):
            params['serialize_func'] = load_object(
                settings['REDIS_ITEMS_SERIALIZER']
            )
        #将参数返回当前类
        return cls(**params)

    @classmethod
    def from_crawler(cls, crawler):
        return cls.from_settings(crawler.settings)
    #将item传递过来,自动触发这个函数,process_item
    def process_item(self, item, spider):
        #创建一个线程,用于存储item,也就是说上一个item还没有存储完,下一个item就可以存储
        return deferToThread(self._process_item, item, spider)
    #实现存储函数
    def _process_item(self, item, spider):
        #生成item_key
        key = self.item_key(item, spider)
        #使用默认的序列化函数,将item序列化为字符串
        data = self.serialize(item)
        #self.server是redis的连接实例
        self.server.rpush(key, data)
        return item
    #用于存储item
    def item_key(self, item, spider):
        """Returns redis key based on given spider.

        Override this function to use a different key depending on the item
        and/or spider.

        """
        # self.key='%(spider)s:items'=%(spider.name)s:items'
        return self.key % {'spider': spider.name} # 格式化字符串

6.queue.py

爬取队列,有三个队列实现,首先它实现了一个父类base,提供一些基本方法与属性

from scrapy.utils.reqser import request_to_dict, request_from_dict

from . import picklecompat
class Base(object):
    """Per-spider base queue class"""

    def __init__(self, server, spider, key, serializer=None):
        """Initialize per-spider redis queue.

        Parameters
        ----------
        server : StrictRedis
            Redis client instance.
        spider : Spider
            Scrapy spider instance.
        key: str
            Redis key where to put and get messages.
        serializer : object
            Serializer object with ``loads`` and ``dumps`` methods.

        """
        if serializer is None:
            # Backward compatibility.
            # TODO: deprecate pickle.
            serializer = picklecompat
        # 当序列化 没有loads函数时 抛出异常
        # 抛出异常的目的就是为了使传过来的序列化必须含有loads函数
        if not hasattr(serializer, 'loads'):
            raise TypeError("serializer does not implement 'loads' function: %r"
                            % serializer)
        if not hasattr(serializer, 'dumps'):
            raise TypeError("serializer '%s' does not implement 'dumps' function: %r"
                            % serializer)

        # 下面的函数当类的所有函数 都可以使用
        self.server = server
        self.spider = spider
        self.key = key % {'spider': spider.name}
        self.serializer = serializer

    # 将request进行编码成字符串
    def _encode_request(self, request):
        """Encode a request object"""
        # 将requests转换为字典
        obj = request_to_dict(request, self.spider)
        # 将字典转换为字符串进行返回
        return self.serializer.dumps(obj)

    # 将已经编码的encoded_request解码为字典
    def _decode_request(self, encoded_request):
        """Decode an request previously encoded"""
        obj = self.serializer.loads(encoded_request)
        # 将dict转换为request objects 可以直接通过下载器进行下载
        return request_from_dict(obj, self.spider)

    # len方法 必须被重载 否则不能使用
    def __len__(self):
        """Return the length of the queue"""
        raise NotImplementedError

    def push(self, request):
        """Push a request"""
        raise NotImplementedError

    def pop(self, timeout=0):
        """Pop a request"""
        raise NotImplementedError

    # 删除指定的self.key
    def clear(self):
        """Clear queue/stack"""
        self.server.delete(self.key)

首先看一下_encode_request() 和_decode_request()方法。我们把一个reques对象存储到数据库中,但数据库无法直接存储对象,多以要将request序列化转化为字符串,而这两个方法分别可以实现序列化和反序列化的操作,这个过程中可以利用pickle库来实现,队列queu在调用push()方法将request 存入数据库时,会调用_encode_request ()方法进行序列化,在调用pop()取出request时,会调用_decode_request()进行反序列化

在父类中,len(),push()和pop()这三个方法都是未实现的,三个方法直接抛出NotImplementedError 异常,因此这个类不能直接使用。那么,必须要实现一个子类来重写这三个方法,而不同的子类就会有不同的实现和不同的功能。

下面三个子类来继承base的三个子类,FifoQueue,PriorityQueue,LifoQueue,他们实现原理的功能。

首先介绍FifoQueue

class FifoQueue(Base):
    """Per-spider FIFO queue"""

    def __len__(self):
        """Return the length of the queue"""
        return self.server.llen(self.key)

    # 重头部插入request
    def push(self, request):
        """Push a request"""
        # 编码request 插入self.key
        self.server.lpush(self.key, self._encode_request(request))

    def pop(self, timeout=0):
        """Pop a request"""
        if timeout > 0:
            data = self.server.brpop(self.key, timeout)
            if isinstance(data, tuple):
                data = data[1]
        else:
            data = self.server.rpop(self.key)
        if data:
            return self._decode_request(data)

这个类继承base类,并重写了__len__()、push()、pop()三个方法,这三个方法都是对server对象的操作。server对象就是一个redis连接对象,我们直接调用其操作redis的方法对数据库进行操作,这里的操作方法有llen() ,lpush(),rpop()等,这就代表此爬虫队列使用了redis的列表。序列化后request会存入列表中,len ()方法获取列表的长度,push()调用了lpush()操作,这代表从列表左侧存入数据,pop()方法中调用了rpop()操作,这代表从列右侧取出数据。

request在列表中存取顺序是左侧进,右侧出,这是有序的进出,即先进先出,此类的名称就叫作FifoQueue

接下来是介绍PriorityQueue。

class PriorityQueue(Base):
    """Per-spider priority queue abstraction using redis' sorted set"""

    def __len__(self):
        """Return the length of the queue"""
        return self.server.zcard(self.key)

    def push(self, request):
        """Push a request"""
        data = self._encode_request(request)
        score = -request.priority
        # We don't use zadd method as the order of arguments change depending on
        # whether the class is Redis or StrictRedis, and the option of using
        # kwargs only accepts strings, not bytes.
        # 使用有序集合实现优先级队列
        self.server.execute_command('ZADD', self.key, score, data)

    def pop(self, timeout=0):
        """
        Pop a request
        timeout not support in this queue class
        """
        # use atomic range/remove using multi/exec
        # 实例化函数 self.server 有一个方法叫做pipeline
        pipe = self.server.pipeline()
        pipe.multi()
        # zrange是从小到大排序后返回第一个值  zremrangebyrank 删除第一个request
        pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0)
        # results 接收的是第一条数据 count删除的元素 返回值为 1 或 0
        results, count = pipe.execute()
        # 只要有一个元素results就是真值
        if results:
            # 将获取到的第一个元素(返回的是个列表) 拿出来 进行解码
            return self._decode_request(results[0])

这里__len__()、push()、pop()方法使用了server对象的zcard(),zadd(),zrange()操作,这里使用的存储结果是有序集合,这个集合中的每个元素都可以设置分数,这个分数就代表优先级。

  • len() 方法调用了zcard()操作,返回的就是有序集合的大小,也就是爬取队列的长度。
  • push()方法调用了zadd()操作,就是向集合中添加元素,这里的分数指定成request的优先级的相反分数,分数低的排在集合前面,即高优先级的request就会在集合的最前面。
  • pop()方法首先调用了zrange()操作,取出集合的第一元素,第一个元素就是最高优先级的request,然后再调用zrangebyrank()操作,将这个元素删除,这个元素删除,这样就完成了取出并删除的操作。

此队列是默认使用的队列,即爬取队列默认是使用有序集合来存储的。

接下来介绍LifoQueue

class LifoQueue(Base):
    """Per-spider LIFO queue."""

    def __len__(self):
        """Return the length of the stack"""
        return self.server.llen(self.key)

    def push(self, request):
        """Push a request"""
        self.server.lpush(self.key, self._encode_request(request))

    def pop(self, timeout=0):
        """Pop a request"""
        if timeout > 0:
            data = self.server.blpop(self.key, timeout)
            if isinstance(data, tuple):
                data = data[1]
        else:
            data = self.server.lpop(self.key)

        if data:
            return self._decode_request(data)


# TODO: Deprecate the use of these names.
SpiderQueue = FifoQueue
SpiderStack = LifoQueue
SpiderPriorityQueue = PriorityQueue

与 FifoQueue不同的是 LifoQueue的pop()方法,他是的是lpop()操作,也就是从左侧出,push()方法依然使用lpush()操作,从左侧入。那么效果就是先进后出,后进先出此类名称叫做 LifoQueue。这个存取方式类似栈的操作,所以也可以称作stackqueue

7. scheduler.py

首先从 setting.py中获取 scheduler的设置。enqueue_request()可以向队列中添加request,核心操作就是调用queue的push()操作,还有一些统计和日志操作。next_request()就是从队列中取request,核心凑就是queue的pop()操作,此时如果队列中还设有request,则request会直接取出来,爬取继续,否则如果队列为空,爬取则重新开始

import importlib
import six

from scrapy.utils.misc import load_object

from . import connection, defaults


# TODO: add SCRAPY_JOB support.
class Scheduler(object):
    """Redis-based scheduler

    Settings
    --------
    SCHEDULER_PERSIST : bool (default: False)
        Whether to persist or clear redis queue.
    SCHEDULER_FLUSH_ON_START : bool (default: False)
        Whether to flush redis queue on start.
    SCHEDULER_IDLE_BEFORE_CLOSE : int (default: 0)
        How many seconds to wait before closing if no message is received.
    SCHEDULER_QUEUE_KEY : str
        Scheduler redis key.
    SCHEDULER_QUEUE_CLASS : str
        Scheduler queue class.
    SCHEDULER_DUPEFILTER_KEY : str
        Scheduler dupefilter redis key.
    SCHEDULER_DUPEFILTER_CLASS : str
        Scheduler dupefilter class.
    SCHEDULER_SERIALIZER : str
        Scheduler serializer.

    """

    def __init__(self, server,
                 persist=False,
                 flush_on_start=False,
                 queue_key=defaults.SCHEDULER_QUEUE_KEY,
                 queue_cls=defaults.SCHEDULER_QUEUE_CLASS,
                 dupefilter_key=defaults.SCHEDULER_DUPEFILTER_KEY,
                 dupefilter_cls=defaults.SCHEDULER_DUPEFILTER_CLASS,
                 idle_before_close=0,
                 serializer=None):
        """Initialize scheduler.

        Parameters
        ----------
        server : Redis
            The redis server instance.
        persist : bool
            Whether to flush requests when closing. Default is False.
        flush_on_start : bool
            Whether to flush requests on start. Default is False.
        queue_key : str
            Requests queue key.
        queue_cls : str
            Importable path to the queue class.
        dupefilter_key : str
            Duplicates filter key.
        dupefilter_cls : str
            Importable path to the dupefilter class.
        idle_before_close : int
            Timeout before giving up.

        """
        if idle_before_close < 0:
            raise TypeError("idle_before_close cannot be negative")

        self.server = server
        self.persist = persist
        self.flush_on_start = flush_on_start
        self.queue_key = queue_key
        self.queue_cls = queue_cls
        self.dupefilter_cls = dupefilter_cls
        self.dupefilter_key = dupefilter_key
        self.idle_before_close = idle_before_close
        self.serializer = serializer
        self.stats = None

    def __len__(self):
        return len(self.queue)

    @classmethod
    def from_settings(cls, settings):
        kwargs = {
            # 将数据持久化
            'persist': settings.getbool('SCHEDULER_PERSIST'),
            'flush_on_start': settings.getbool('SCHEDULER_FLUSH_ON_START'),
            'idle_before_close': settings.getint('SCHEDULER_IDLE_BEFORE_CLOSE'),
        }

        # If these values are missing, it means we want to use the defaults.
        optional = {
            # TODO: Use custom prefixes for this settings to note that are
            # specific to scrapy-redis.
            'queue_key': 'SCHEDULER_QUEUE_KEY',
            'queue_cls': 'SCHEDULER_QUEUE_CLASS',
            'dupefilter_key': 'SCHEDULER_DUPEFILTER_KEY',
            # We use the default setting name to keep compatibility.
            'dupefilter_cls': 'DUPEFILTER_CLASS',
            'serializer': 'SCHEDULER_SERIALIZER',
        }
        # 将在设置中定义好的键更新进入kwargs
        for name, setting_name in optional.items():
            val = settings.get(setting_name)
            if val:
                kwargs[name] = val

        # Support serializer as a path to a module.
        if isinstance(kwargs.get('serializer'), six.string_types):
            kwargs['serializer'] = importlib.import_module(kwargs['serializer'])

        server = connection.from_settings(settings)
        # Ensure the connection is working.
        # 验证server是否连接成功
        server.ping()

        return cls(server=server, **kwargs)

    @classmethod
    def from_crawler(cls, crawler):
        instance = cls.from_settings(crawler.settings)
        # FIXME: for now, stats are only supported from this constructor
        instance.stats = crawler.stats
        return instance

    def open(self, spider):
        self.spider = spider

        try:
            self.queue = load_object(self.queue_cls)(
                server=self.server,
                spider=spider,
                key=self.queue_key % {'spider': spider.name},
                serializer=self.serializer,
            )
        except TypeError as e:
            raise ValueError("Failed to instantiate queue class '%s': %s",
                             self.queue_cls, e)

        self.df = load_object(self.dupefilter_cls).from_spider(spider)

        if self.flush_on_start:
            self.flush()
        # notice if there are requests already in the queue to resume the crawl
        if len(self.queue):
            spider.log("Resuming crawl (%d requests scheduled)" % len(self.queue))

    def close(self, reason):
        if not self.persist:
            self.flush()

    def flush(self):
        self.df.clear()
        self.queue.clear()

    # 入队函数
    def enqueue_request(self, request):
        # self.df = load_object(self.dupefilter_cls).from_spider(spider)
        # = defaults.SCHEDULER_DUPEFILTER_CLASS =  'scrapy_redis.dupefilter.RFPDupeFilter'
        # self.df.request_seen(request) 返回的bool值 True代表request存在
        # not request.dont_filter 在默认的情况下 返回True
        # 当我们选择的是过滤 而且 request已经入队的时候 我们返回Flase
        if not request.dont_filter and self.df.request_seen(request):
            self.df.log(request, self.spider)
            return False
        # 这个用不到 默认的是None
        if self.stats:
            self.stats.inc_value('scheduler/enqueued/redis', spider=self.spider)
        # 入队 默认使用优先级队列
        self.queue.push(request)
        return True

    # 出队函数
    def next_request(self):
        block_pop_timeout = self.idle_before_close
        # 弹出一条数据
        request = self.queue.pop(block_pop_timeout)
        if request and self.stats:
            self.stats.inc_value('scheduler/dequeued/redis', spider=self.spider)
        # 返回request 给引擎 引擎在给 下载器
        return request

    def has_pending_requests(self):
        return len(self) > 0

8. spider.py

from scrapy import signals
from scrapy.exceptions import DontCloseSpider
from scrapy.spiders import Spider, CrawlSpider

from . import connection, defaults
from .utils import bytes_to_str


class RedisMixin(object):
    """Mixin class to implement reading urls from a redis queue."""
    redis_key = None
    redis_batch_size = None
    redis_encoding = None

    # Redis client placeholder.
    server = None

    def start_requests(self):
        """Returns a batch of start requests from redis."""
        return self.next_requests()

    def setup_redis(self, crawler=None):
        """Setup redis connection and idle signal.

        This should be called after the spider has set its crawler object.
        """
        if self.server is not None:
            return

        if crawler is None:
            # We allow optional crawler argument to keep backwards
            # compatibility.
            # XXX: Raise a deprecation warning.
            crawler = getattr(self, 'crawler', None)

        if crawler is None:
            raise ValueError("crawler is required")

        settings = crawler.settings

        if self.redis_key is None:
            self.redis_key = settings.get(
                'REDIS_START_URLS_KEY', defaults.START_URLS_KEY,
            )

        self.redis_key = self.redis_key % {'name': self.name}

        if not self.redis_key.strip():
            raise ValueError("redis_key must not be empty")

        if self.redis_batch_size is None:
            # TODO: Deprecate this setting (REDIS_START_URLS_BATCH_SIZE).
            self.redis_batch_size = settings.getint(
                'REDIS_START_URLS_BATCH_SIZE',
                settings.getint('CONCURRENT_REQUESTS'),
            )

        try:
            self.redis_batch_size = int(self.redis_batch_size)
        except (TypeError, ValueError):
            raise ValueError("redis_batch_size must be an integer")

        if self.redis_encoding is None:
            self.redis_encoding = settings.get('REDIS_ENCODING', defaults.REDIS_ENCODING)

        self.logger.info("Reading start URLs from redis key '%(redis_key)s' "
                         "(batch size: %(redis_batch_size)s, encoding: %(redis_encoding)s",
                         self.__dict__)

        self.server = connection.from_settings(crawler.settings)
        # The idle signal is called when the spider has no requests left,
        # that's when we will schedule new requests from redis queue
        crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)

    def next_requests(self):
        """Returns a request to be scheduled or none."""
        # 使用默认的reids_keys 是一个列表 否者就是集合
        use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET)
        # use_set 是个False 则返回self.server.lpop(列表类型) 否则返回self.server.spop(集合类型)
        fetch_one = self.server.spop if use_set else self.server.lpop
        # XXX: Do we need to use a timeout here?
        found = 0
        # TODO: Use redis pipeline execution.
        while found < self.redis_batch_size:
            # 从数据库中取出起始url数据 返回的是一个列表的
            data = fetch_one(self.redis_key)
            # 如果是空 则直接终止循环
            if not data:
                # Queue empty.
                break
            # 获取到的起始url 转换为
            req = self.make_request_from_data(data)
            if req:
                yield req
                found += 1
            else:
                self.logger.debug("Request not made from data: %r", data)
        # 如果上面的while 不执行 found 一直是0
        # 如果上面执行了found 不等于0 执行下面的if 语句
        # 如果redis_keys 起始URL不存在 提示 没有request
        if found:
            self.logger.debug("Read %s requests from '%s'", found, self.redis_key)

    # 返回的是request实例 是通过来自redis的data数据
    def make_request_from_data(self, data):
        """Returns a Request instance from data coming from Redis.

        By default, ``data`` is an encoded URL. You can override this method to
        provide your own message decoding.

        Parameters
        ----------
        data : bytes
            Message from redis.

        """
        # 将获取到的bytes类型数据 转换为字符串
        url = bytes_to_str(data, self.redis_encoding)
        return self.make_requests_from_url(url)

    def schedule_next_requests(self):
        """Schedules a request if available"""
        # TODO: While there is capacity, schedule a batch of redis requests.
        for req in self.next_requests():
            self.crawler.engine.crawl(req, spider=self)

    def spider_idle(self):
        """Schedules a request if available, otherwise waits."""
        # XXX: Handle a sentinel to close the spider.
        self.schedule_next_requests()
        raise DontCloseSpider


class RedisSpider(RedisMixin, Spider):
    """Spider that reads urls from redis queue when idle.

    Attributes
    ----------
    redis_key : str (default: REDIS_START_URLS_KEY)
        Redis key where to fetch start URLs from..
    redis_batch_size : int (default: CONCURRENT_REQUESTS)
        Number of messages to fetch from redis on each attempt.
    redis_encoding : str (default: REDIS_ENCODING)
        Encoding to use when decoding messages from redis queue.

    Settings
    --------
    REDIS_START_URLS_KEY : str (default: ":start_urls")
        Default Redis key where to fetch start URLs from..
    REDIS_START_URLS_BATCH_SIZE : int (deprecated by CONCURRENT_REQUESTS)
        Default number of messages to fetch from redis on each attempt.
    REDIS_START_URLS_AS_SET : bool (default: False)
        Use SET operations to retrieve messages from the redis queue. If False,
        the messages are retrieve using the LPOP command.
    REDIS_ENCODING : str (default: "utf-8")
        Default encoding to use when decoding messages from redis queue.

    """

    @classmethod
    def from_crawler(self, crawler, *args, **kwargs):
        obj = super(RedisSpider, self).from_crawler(crawler, *args, **kwargs)
        obj.setup_redis(crawler)
        return obj


class RedisCrawlSpider(RedisMixin, CrawlSpider):
    """Spider that reads urls from redis queue when idle.

    Attributes
    ----------
    redis_key : str (default: REDIS_START_URLS_KEY)
        Redis key where to fetch start URLs from..
    redis_batch_size : int (default: CONCURRENT_REQUESTS)
        Number of messages to fetch from redis on each attempt.
    redis_encoding : str (default: REDIS_ENCODING)
        Encoding to use when decoding messages from redis queue.

    Settings
    --------
    REDIS_START_URLS_KEY : str (default: ":start_urls")
        Default Redis key where to fetch start URLs from..
    REDIS_START_URLS_BATCH_SIZE : int (deprecated by CONCURRENT_REQUESTS)
        Default number of messages to fetch from redis on each attempt.
    REDIS_START_URLS_AS_SET : bool (default: True)
        Use SET operations to retrieve messages from the redis queue.
    REDIS_ENCODING : str (default: "utf-8")
        Default encoding to use when decoding messages from redis queue.

    """

    @classmethod
    def from_crawler(self, crawler, *args, **kwargs):
        obj = super(RedisCrawlSpider, self).from_crawler(crawler, *args, **kwargs)
        obj.setup_redis(crawler)
        return obj

9.utils.py

将bytes类型转化为字符串

import six
#将bytes类型转化为字符串
def bytes_to_str(s, encoding='utf-8'):
    """Returns a str if a bytes object is given."""
    if six.PY3 and isinstance(s, bytes):
        return s.decode(encoding)
    return s


你可能感兴趣的:(爬虫)