一、改写程序
(一)在爬虫文件中:
第1步:导入模块
from scrapy_redis.spiders import RedisSpider
第2步:修改继承的父类 将class DangdangSpider(scrapy.Spider): 改成:
class DangdangSpider(RedisSpider):
第3步: 把start_urls 整行删掉,写成 reids_key=‘爬虫文件名字’。
#start_urls = ['http://book.dangdang.com/'] 注释掉了,就是删掉了
redis_key = 'dangdang' #这个‘dangdang’其实就是爬虫类中的name属性值
备注:这个redis_key是为了以后在redis中控制爬虫启动的。爬虫的第一个url,就是在redis中通过这个发送出去的。
第4步:将print(item)改成yield item,传递给管道。
(二)在settings文件中:将项目的管道和调度器配置成基于scrapy-redis组件
第1步:在空白处将下面3行代码粘贴进去
#去重过滤(使用scrapy-redis组件的去重队列)
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
#scheduler队列(使用scrapy-redis组件自己的调度器)
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
#数据持久化(是否允许暂停)
SCHEDULER_PERSIST = True
第2步,开启管道,即在ITEM_PIPELINES行处取消注释,并修改成:
ITEM_PIPELINES = {
'scrapy_redis.pipelines.RedisPipeline': 400,
}
第3步(可选):将LOG_LEVEL = ‘WARNING’ 注释掉。
(三)开启redis后运行爬虫 在安装路径(桌面)找到redis文件夹,点击进去。 使2个cmd都开着,再scrapy crawl dangdang运行爬虫文件,结果: 此时,在redis-cli窗口中写入:
lpush dangdang https://book.dangdang.com/
也就是在Redis服务器上,推入一个开始的url链接,以启动爬取。 再次运行爬虫之后,我们在在redis-cli窗口中写入:keys * 可以看到redis中已有了爬取结果。 (之所以没有 "dangdang:requests"是因为已经爬完了,就没有待爬取的了。)
二、完整的代码 1、爬虫文件:
# -*- coding: utf-8 -*-
import scrapy
from copy import deepcopy
from scrapy_redis.spiders import RedisSpider # 第一步
class DangdangSpider(RedisSpider): # 第二步
name = 'dangdang'
allowed_domains = ['dangdang.com']
redis_key = 'dangdang' #第三步
def parse(self, response):
div_list = response.xpath('//div[@class="con flq_body"]/div')
for div in div_list:
item = {}
# 获取大分类
item['b_cate'] = div.xpath('./dl/dt//text()').extract()
item['b_cate'] = [i.strip() for i in item['b_cate'] if len(i.strip())>0]
dl_list = div.xpath('.//dl[@class="inner_dl"]')
for dl in dl_list:
# 获取中分类
item['m_cate'] = dl.xpath('./dt//text()').extract()
item['m_cate'] = [i.strip() for i in item['m_cate'] if len(i.strip()) > 0]
# 获取小分类
a_list = dl.xpath('./dd/a')
for a in a_list:
item['s_cate'] = a.xpath('./text()').extract_first()
item['s_href'] = a.xpath('./@href').extract_first()
if item['s_href'] is not None:
yield scrapy.Request(
url=item['s_href'],
callback=self.parse_book_list,
meta={'item':deepcopy(item)}
)
#print(item) #这里的打印item,结果不包含书名和封面
def parse_book_list(self,response):
item = response.meta.get('item')
li_list = response.xpath('//ul[@class="list_aa "]/li')
for li in li_list:
# 图片的url
item['book_img'] = li.xpath('./a[@class="img"]/img/@data-original').extract_first()
# 数据的名字
item['book_name'] = li.xpath('./p[@class="name"]//text()').extract_first()
yield item #第4步
2、settings文件:
# -*- coding: utf-8 -*-
# Scrapy settings for dangd project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'dangd'
SPIDER_MODULES = ['dangd.spiders']
NEWSPIDER_MODULE = 'dangd.spiders'
#去重过滤
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" #第一步
#scheduler队列
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
#数据持久化
SCHEDULER_PERSIST = True
#LOG_LEVEL = 'WARNING' 第三步
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'dangd (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'dangd.middlewares.DangdSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'dangd.middlewares.DangdDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = { #第二步
'scrapy_redis.pipelines.RedisPipeline': 400,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
|