python - Scrapy/Python:在产生的请求完成后运行逻辑
问题描述
我所做的:
def parse(self, response):
products_urls = response.css('.product-item a::attr(href)').extract()
for product_url in product_urls:
yield Request(product_url, callback=self.parse_product)
print( "Continue doing stuff...." )
def parse_product(self, response):
title = response.css('h1::text').extract_first()
print( title )
}
在此示例中,代码将首先输出Continue doing stuff..
,然后打印产品标题。我希望它以其他方式运行,首先执行请求并打印标题,然后才打印Continue doing stuff..
更新:@Georgiy 在评论中询问我是否需要以前抓取的产品数据。
答案是肯定的,这是一个简化的例子。获取数据后,我想操作该数据。
解决方案
您可以将逻辑移动到parse_product
函数中。例如:
def parse(self, response):
products_urls = response.css('.product-item a::attr(href)').extract()
self.count = len(products_urls)
if self.count == 0:
self.onEnd()
else:
for product_url in product_urls:
yield Request(product_url, callback=self.parse_product)
def onEnd(self):
print( "Continue doing stuff...." )
def parse_product(self, response):
title = response.css('h1::text').extract_first()
print( title )
self.count -= 1
if (self.count == 0):
self.onEnd()