今天我们来聊一聊Scrapy爬虫中的请求处理与返回策略。你有没有遇到过一个Item需要由多个请求组成的情况?如果是的话,那么对请求的处理和决定是否返回处理过的Item对象就变得格外重要。看一下Scrapy中的相关策略,实现爬虫的`完美康复`。
import scrapy
class MySpider(scrapy.Spider):
name = "example"
def start_requests(self):
urls = [
'http://www.example.com/page1',
'http://www.example.com/page2',
'http://www.example.com/page3',
'http://www.example.com/page4',
'http://www.example.com/page5',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse, meta={'download_timeout': 3})
def parse(self, response):
# 解析HTML内容,提取数据
data = response.css('.my-class::text').get()
# 创建Item对象
item = {}
item['data'] = data
# 判断是否获取到了完整的Item数据
if item['data']:
yield item
else:
self.logger.warning('Incomplete item: missing data')
# 判断是否所有请求都已处理完毕
if all(response.request.url.endswith(str(i)) for i in range(1, 6)):
self.logger.info('All requests processed')