Scrapy_redis在scrapy的基礎(chǔ)上實現(xiàn)了更多,更強大的功能,具體體現(xiàn)在:reqeust去重,爬蟲持久化,和輕松實現(xiàn)分布式,安裝命令如下:
pip3 install scrapy-redis
Scrapy-redis提供了下面四種組件:
1.Scheduler
2.Duplication Filter
3.Item Pipeline
4.Base Spider
Scrapy本身不支持爬蟲分布式,scrapy-redis 的解決是把這個Scrapy queue換成redis數(shù)據(jù)庫,從同一個redis-server存放要爬取的request,便能讓多個spider去同一個數(shù)據(jù)庫里讀取。
Scheduler
注意!
原來的Scheduler已經(jīng)無法使用,所以使用Scrapy-redis的scheduler組件。
Duplication Filter
Scrapy中用集合實現(xiàn)這個request去重功能,Scrapy中把已經(jīng)發(fā)送的request指紋放入到一個集合中,把下一個request的指紋拿到集合中比對,如果該指紋存在于集合中,說明這個request發(fā)送過了,如果沒有則繼續(xù)操作。
Item Pipeline
引擎將Spider返回的爬取到的Item給Item Pipeline,scrapy-redis 的Item Pipeline將爬取到的 Item 存?redis的 items queue。
Base Spider
不在使用scrapy原有的Spider類,重寫的RedisSpider繼承了Spider和RedisMixin這兩個類,RedisMixin是用來從redis讀取url的類。
要實現(xiàn)分布式爬蟲,需要在settings中做如下設(shè)置
Scrapy settings for example project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
SPIDER_MODULES = ['example.spiders']
NEWSPIDER_MODULE = 'example.spiders'
# 默認的User-Agent
USER_AGENT = 'scrapy-redis (+https://github.com/rolando/scrapy-redis)'
#這里表示啟用scrapy-redis里的去重組件,
不再使用scrapy默認的去重
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
#使用了scrapy-redis里面的調(diào)度器組件,不再使用scrapy默認的調(diào)度器
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
#允許暫停,redis請求的記錄不會丟失,不清除
Redis隊列,可以恢復(fù)和暫停
SCHEDULER_PERSIST = True
#下面這些是request的隊列模式
#一般情況下使用第一種
#scrapy-redis默認的請求隊列形式(有自己的優(yōu)先級順序)
#是按照redis的有序集合排序出隊列的
#SCHEDULER_QUEUE_CLASS = "scrapy_redis.queue.SpiderPriorityQueue"
#這個是啟用了堆的形式,請求先進先出
#SCHEDULER_QUEUE_CLASS = "scrapy_redis.queue.SpiderQueue"
#使用了棧的形式,請求先進后出
#SCHEDULER_QUEUE_CLASS = "scrapy_redis.queue.SpiderStack"
# scrapy_redis.pipelines.RedisPipeline 必須啟用,才能夠?qū)?shù)據(jù)存儲到redis數(shù)據(jù)庫中
ITEM_PIPELINES = {
'example.pipelines.ExamplePipeline': 300,
'scrapy_redis.pipelines.RedisPipeline': 400,
}
# log日志等級(可選)
# LOG_LEVEL = 'DEBUG'
# 指定要存儲的redis的主機的ip,
默認存儲在127.0.0.1
REDIS_HOST = 'redis的主機的ip'
# 定要存儲的redis的主機的port,
默認6379
REDIS_PORT = '6379'
# Introduce an artifical delay to make use of parallelism. to speed up the
# crawl.
#下載延時
DOWNLOAD_DELAY = 1