一、爬虫文件
使用RedisSpider为继承父类,添加redis_key
python
import scrapy
from ..items import NewsItem
from scrapy_redis import spiders
class CbsnewsSpiderSpider(spiders.RedisSpider):
name = "abc_spider"
# allowed_domains = ["www.abc.com"]
# start_urls = ["https://www.abc.com/"]
redis_key = 'abc:start_urls' # redis队列关键字,使用 lpush abc:start_urls https://www.abc.com/ 放入初始网址,程序自动GET请求
def parse(self, response):
"""
第一层:解析自动GET请求的初始网址
:param response:
:return:
"""
abc_list = response.xpath('//nav[@class="header__nav"]//a/@href').extract()
if not abc_list:
return
for column_url in abc_list:
yield scrapy.Request(column_url, callback=self.abc_source, meta={'column_url': column_url})
def abc_source(self,response):
"""
第二层:解析第一层获取并请求回来的网址
:param response:
:return:
"""
column_url = response.meta['column_url']
print(column_url)
pass
二、settings.py配置
项目settings.py文件增加下面代码即可
python
# 增加redis地址、端口
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
# 配置scrapy-redis调度器
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
# 配置爬取去重
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
# 断点续连,不用从头开始爬
SCHEDULER_PERSIST = True