1. 程式人生 > >python高級之scrapy-redis

python高級之scrapy-redis

int art sts {} param 本質 opened div pipe

目錄:

  • scrapy-redis組件

  • scrapy-redis配置示例

一、scrapy-redis組件

1、scrapy-redis簡介:

scrapy-redis是一個基於redis的scrapy組件,通過它可以快速實現簡單分布式爬蟲程序,該組件本質上提供了三大功能:

  • scheduler - 調度器
  • dupefilter - URL去重規則(被調度器使用)
  • pipeline - 數據持久化

2、url去重

多爬蟲分布式並發,如何保證調用的url不重復。需要把爬蟲隊列和調度器,去重規則,提取到redis中。

組件: scrapy-redis,將去重規則和調度器放置到redis中。

流程:連接redis,指定調度器時,調用去重規則.request_seen方法。

技術分享
 1 定義去重規則(被調度器調用並應用)
 2  
 3     a. 內部會使用以下配置進行連接Redis
 4  
 5         # REDIS_HOST = ‘localhost‘                            # 主機名
 6         # REDIS_PORT = 6379                                   # 端口
 7         # REDIS_URL = ‘redis://user:pass@hostname:9001‘       # 連接URL(優先於以上配置)
8 # REDIS_PARAMS = {} # Redis連接參數 默認:REDIS_PARAMS = {‘socket_timeout‘: 30,‘socket_connect_timeout‘: 30,‘retry_on_timeout‘: True,‘encoding‘: REDIS_ENCODING,}) 9 # REDIS_PARAMS[‘redis_cls‘] = ‘myproject.RedisClient‘ # 指定連接Redis的Python模塊 默認:redis.StrictRedis
10 # REDIS_ENCODING = "utf-8" # redis編碼類型 默認:‘utf-8‘ 11 12 b. 去重規則通過redis的集合完成,集合的Key為: 13 14 key = defaults.DUPEFILTER_KEY % {timestamp: int(time.time())} 15 默認配置: 16 DUPEFILTER_KEY = dupefilter:%(timestamp)s 17 18 c. 去重規則中將url轉換成唯一標示,然後在redis中檢查是否已經在集合中存在 19 20 from scrapy.utils import request 21 from scrapy.http import Request 22 23 req = Request(url=http://www.cnblogs.com/wupeiqi.html) 24 result = request.request_fingerprint(req) 25 print(result) # 8ea4fd67887449313ccc12e5b6b92510cc53675c 26 27 28 PS: 29 - URL參數位置不同時,計算結果一致; 30 - 默認請求頭不在計算範圍,include_headers可以設置指定請求頭 31 示例: 32 from scrapy.utils import request 33 from scrapy.http import Request 34 35 req = Request(url=http://www.baidu.com?name=8&id=1,callback=lambda x:print(x),cookies={k1:vvvvv}) 36 result = request.request_fingerprint(req,include_headers=[cookies,]) 37 38 print(result) 39 40 req = Request(url=http://www.baidu.com?id=1&name=8,callback=lambda x:print(x),cookies={k1:666}) 41 42 result = request.request_fingerprint(req,include_headers=[cookies,]) 43 44 print(result) 45 46 """ 47 # Ensure all spiders share same duplicates filter through redis. 48 # DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
View Code

ps.有關爬蟲隊列和調度器,去重規則詳見

http://www.cnblogs.com/wangshuyang/p/7717263.html

3、調度器

技術分享
 1 """
 2 調度器,調度器使用PriorityQueue(有序集合)、FifoQueue(列表)、LifoQueue(列表)進行保存請求,並且使用RFPDupeFilter對URL去重
 3      
 4     a. 調度器
 5         SCHEDULER_QUEUE_CLASS = ‘scrapy_redis.queue.PriorityQueue‘          # 默認使用優先級隊列(默認),其他:PriorityQueue(有序集合),FifoQueue(列表)、LifoQueue(列表)
 6         SCHEDULER_QUEUE_KEY = ‘%(spider)s:requests‘                         # 調度器中請求存放在redis中的key
 7         SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat"                  # 對保存到redis中的數據進行序列化,默認使用pickle
 8         SCHEDULER_PERSIST = True                                            # 是否在關閉時候保留原來的調度器和去重記錄,True=保留,False=清空
 9         SCHEDULER_FLUSH_ON_START = True                                     # 是否在開始之前清空 調度器和去重記錄,True=清空,False=不清空
10         SCHEDULER_IDLE_BEFORE_CLOSE = 10                                    # 去調度器中獲取數據時,如果為空,最多等待時間(最後沒數據,未獲取到)。
11         SCHEDULER_DUPEFILTER_KEY = ‘%(spider)s:dupefilter‘                  # 去重規則,在redis中保存時對應的key
12         SCHEDULER_DUPEFILTER_CLASS = ‘scrapy_redis.dupefilter.RFPDupeFilter‘# 去重規則對應處理的類
13  
14  
15 """
16 # Enables scheduling storing requests queue in redis.
17 SCHEDULER = "scrapy_redis.scheduler.Scheduler"
18  
19 # Default requests serializer is pickle, but it can be changed to any module
20 # with loads and dumps functions. Note that pickle is not compatible between
21 # python versions.
22 # Caveat: In python 3.x, the serializer must return strings keys and support
23 # bytes as values. Because of this reason the json or msgpack module will not
24 # work by default. In python 2.x there is no such issue and you can use
25 # ‘json‘ or ‘msgpack‘ as serializers.
26 # SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat"
27  
28 # Don‘t cleanup redis queues, allows to pause/resume crawls.
29 # SCHEDULER_PERSIST = True
30  
31 # Schedule requests using a priority queue. (default)
32 # SCHEDULER_QUEUE_CLASS = ‘scrapy_redis.queue.PriorityQueue‘
33  
34 # Alternative queues.
35 # SCHEDULER_QUEUE_CLASS = ‘scrapy_redis.queue.FifoQueue‘
36 # SCHEDULER_QUEUE_CLASS = ‘scrapy_redis.queue.LifoQueue‘
37  
38 # Max idle time to prevent the spider from being closed when distributed crawling.
39 # This only works if queue class is SpiderQueue or SpiderStack,
40 # and may also block the same time when your spider start at the first time (because the queue is empty).
41 # SCHEDULER_IDLE_BEFORE_CLOSE = 10  
View Code

4、數據持久化

技術分享
1 2. 定義持久化,爬蟲yield Item對象時執行RedisPipeline
2      
3     a. 將item持久化到redis時,指定key和序列化函數
4      
5         REDIS_ITEMS_KEY = %(spider)s:items
6         REDIS_ITEMS_SERIALIZER = json.dumps
7      
8     b. 使用列表保存item數據
View Code

5、起始URL相關

技術分享
 1 """
 2 起始URL相關
 3  
 4     a. 獲取起始URL時,去集合中獲取還是去列表中獲取?True,集合;False,列表
 5         REDIS_START_URLS_AS_SET = False    # 獲取起始URL時,如果為True,則使用self.server.spop;如果為False,則使用self.server.lpop
 6     b. 編寫爬蟲時,起始URL從redis的Key中獲取
 7         REDIS_START_URLS_KEY = ‘%(name)s:start_urls‘
 8          
 9 """
10 # If True, it uses redis‘ ``spop`` operation. This could be useful if you
11 # want to avoid duplicates in your start urls list. In this cases, urls must
12 # be added via ``sadd`` command or you will get a type error from redis.
13 # REDIS_START_URLS_AS_SET = False
14  
15 # Default start urls key for RedisSpider and RedisCrawlSpider.
16 # REDIS_START_URLS_KEY = ‘%(name)s:start_urls‘
View Code

二、scrapy-redis配置示例

1、示例文件

技術分享
 1 # DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
 2 #
 3 #
 4 # from scrapy_redis.scheduler import Scheduler
 5 # from scrapy_redis.queue import PriorityQueue
 6 # SCHEDULER = "scrapy_redis.scheduler.Scheduler"
 7 # SCHEDULER_QUEUE_CLASS = ‘scrapy_redis.queue.PriorityQueue‘          # 默認使用優先級隊列(默認),其他:PriorityQueue(有序集合),FifoQueue(列表)、LifoQueue(列表)
 8 # SCHEDULER_QUEUE_KEY = ‘%(spider)s:requests‘                         # 調度器中請求存放在redis中的key
 9 # SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat"                  # 對保存到redis中的數據進行序列化,默認使用pickle
10 # SCHEDULER_PERSIST = True                                            # 是否在關閉時候保留原來的調度器和去重記錄,True=保留,False=清空
11 # SCHEDULER_FLUSH_ON_START = False                                    # 是否在開始之前清空 調度器和去重記錄,True=清空,False=不清空
12 # SCHEDULER_IDLE_BEFORE_CLOSE = 10                                    # 去調度器中獲取數據時,如果為空,最多等待時間(最後沒數據,未獲取到)。
13 # SCHEDULER_DUPEFILTER_KEY = ‘%(spider)s:dupefilter‘                  # 去重規則,在redis中保存時對應的key
14 # SCHEDULER_DUPEFILTER_CLASS = ‘scrapy_redis.dupefilter.RFPDupeFilter‘# 去重規則對應處理的類
15 #
16 #
17 #
18 # REDIS_HOST = ‘10.211.55.13‘                           # 主機名
19 # REDIS_PORT = 6379                                     # 端口
20 # # REDIS_URL = ‘redis://user:pass@hostname:9001‘       # 連接URL(優先於以上配置)
21 # # REDIS_PARAMS  = {}                                  # Redis連接參數             默認:REDIS_PARAMS = {‘socket_timeout‘: 30,‘socket_connect_timeout‘: 30,‘retry_on_timeout‘: True,‘encoding‘: REDIS_ENCODING,})
22 # # REDIS_PARAMS[‘redis_cls‘] = ‘myproject.RedisClient‘ # 指定連接Redis的Python模塊  默認:redis.StrictRedis
23 # REDIS_ENCODING = "utf-8"                              # redis編碼類型             默認:‘utf-8‘
View Code

2、爬蟲文件

技術分享
 1 import scrapy
 2 
 3 
 4 class ChoutiSpider(scrapy.Spider):
 5     name = "chouti"
 6     allowed_domains = ["chouti.com"]
 7     start_urls = (
 8         http://www.chouti.com/,
 9     )
10 
11     def parse(self, response):
12         for i in range(0,10):
13             yield
View Code

python高級之scrapy-redis