Scrapy-7.Scrapy-redis

6570 ワード

本住所:https://www.jianshu.com/p/3de01adfff23

概要

scrapy-redisは、Redisに基づくScrapyコンポーネントである.主に次の機能があります.
  • 分散キャプチャデータは、複数の爬虫類インスタンスに同じRedisキューを使用させることができ、広範なマルチドメインキャプチャに非常に適しています.
  • 分散処理データキャプチャされたItemsは、redisキューにプッシュされます.これは、共有されたitemsキューを通じて、必要に応じて後期処理データの数を自分で決定できることを意味します.
  • プラグイン・アンド・プレイが提供するScheduler + Duplication,Item Pipeline,Base Spidersのコンポーネントはすべてプラグイン・アンド・プレイで、非常に便利です.

  • 分散型を構築するスキームは、masterslaveの方式を採用しており、slaveで生成されたurlは、masterにリモートで送信され、masterRedisデータベースを使用して、キャプチャが必要なurlキューを格納することが原理である.slaveは、次のキャプチャurlを取得し、masterから遠隔で取得する.
    このようにして、すべてのSpiderがキャプチャしたアドレスがmasterによって統一的にスケジューリングされ、Redissetに保存されることにより、ブレークポイント継続機能が実現される.
    さらにscrapy-redisは、キャプチャされたすべてのアドレスに指紋を生成して保存し、urlの重複キャプチャを回避することができる.

    インストール

    scrapy-redisRedisに基づいているので、使用する前にRedisデータベースをインストールする必要があります.
    分散を構成する場合は、redisのリモート接続を開き、アクセスパスワードを構成する必要があります.scrapy-redisモジュールのインストールは比較的簡単で、pipでインストールすればよい.
    pip install scrapy-redis
    

    Scrapy-redisの使い方

    scrapy-redisのインストールが完了したら、Scrapyプロジェクトにいくつかの構成オプションを追加するだけでscrapy-redisコンポーネントを有効にできます.
    # Enables scheduling storing requests queue in redis.
    SCHEDULER = "scrapy_redis.scheduler.Scheduler"
    
    # Ensure all spiders share same duplicates filter through redis.
    DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
    
    # 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
    
    # Store scraped item in redis for post-processing.
    ITEM_PIPELINES = {
        'scrapy_redis.pipelines.RedisPipeline': 300
    }
    
    # The item pipeline serializes and stores the items in this redis key.
    #REDIS_ITEMS_KEY = '%(spider)s:items'
    
    # The items serializer is by default ScrapyJSONEncoder. You can use any
    # importable path to a callable object.
    #REDIS_ITEMS_SERIALIZER = 'json.dumps'
    
    # Specify the host and port to use when connecting to Redis (optional).
    #REDIS_HOST = 'localhost'
    #REDIS_PORT = 6379
    
    # Specify the full Redis URL for connecting (optional).
    # If set, this takes precedence over the REDIS_HOST and REDIS_PORT settings.
    #REDIS_URL = 'redis://user:pass@hostname:9001'
    
    # Custom redis client parameters (i.e.: socket timeout, etc.)
    #REDIS_PARAMS  = {}
    # Use custom redis client class.
    #REDIS_PARAMS['redis_cls'] = 'myproject.RedisClient'
    
    # If True, it uses redis' ``SPOP`` operation. You have to use the ``SADD``
    # command to add URLs to the redis queue. This could be useful if you
    # want to avoid duplicates in your start urls list and the order of
    # processing does not matter.
    #REDIS_START_URLS_AS_SET = False
    
    # Default start urls key for RedisSpider and RedisCrawlSpider.
    #REDIS_START_URLS_KEY = '%(name)s:start_urls'
    
    # Use other encoding than utf-8 for redis.
    #REDIS_ENCODING = 'latin1'
    

    以上に列挙した構成文は、構成が必要な部分を選択し、Scrapy項目のsettings.pyファイルにコピーすればよい.

    コアコンポーネント

    scrapy-redisを有効にするには、2つの設定項目を構成する必要があります.
    SCHEDULER = "scrapy_redis.scheduler.Scheduler"
    DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
    

    これはscrapy-redisの2つのコアコンポーネントであり、ほとんどの論理を実現している.

    Redis接続の構成

    Redisを構成する方法は2つあります.1つは、パラメータによって構成されます.
    REDIS_HOST = 'localhost'
    REDIS_PORT = 6379
    REDIS_PASSWORD = 'foobared'
    

    もう1つは、urlアドレスによって構成される.
    REDIS_URL = 'redis://user:password@hostname:9001'
    
    urlアドレスは、次の3つのフォーマットをサポートします.
    redis://[:password]@host:port/db rediss://[:password]@host:port/db unix://[:password]@/path/to/socket.sock?db=db

    スケジュールキューの構成


    また、フィールドを設定してキューのスケジューリング方法を構成することもできます.スケジュールには、次の3つがあります.
    #        ,    ,  redis      
    SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue'
    #       
    SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.FifoQueue'
    #       
    SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.LifoQueue'
    

    構成時にどちらかを選択できます.

    ブレークポイントを設定して登る

    scrapy-redisは、デポジットされた指紋およびランディングキューをRedisデータベースに格納するので、ブレークポイント継続機能を実現することができる.
    まず、持続的な構成をオンにする必要があります.この設定をTrueに設定すると、Scrapyは終了時にRedisのキューを空にしません.
    SCHEDULER_PERSIST = True
    

    重い指紋とキューを残しておくと、次のスナップを開くと前回のキューを再開します.

    Pipelineの設定

    scrapy-redisには、各分散型のslaveがキャプチャしたitemをmasterに転送できる機能があり、これにより、すべてのキャプチャされたデータが統一されたmasterに保存される.
    しかし、この機能はキャプチャの速度に大きな影響を及ぼすため、大規模なキャプチャでは一般的にこのオプションはオンになりません.
    ITEM_PIPELINES = {
        'scrapy_redis.pipelines.RedisPipeline': 300
    }
    

    シリーズ記事:
  • Scrapy-1.強力で包括的なPython爬虫類フレーム
  • Scrapy-2.Spiders
  • Scrapy-3.SelectorとRequest
  • Scrapy-4.Middleware
  • Scrapy-5.Items
  • Scrapy-6.Settings
  • Scrapy-7.Scrapy-redis
  • Scrapy-8.Scrapyd
  • Scrapy-9.よくある質問