有多种方法来解析响应的Scrapy蜘蛛编写合同的最佳方法是什么? 我看到这个answer,但它听起来不太清楚。具有多种解析方法的Scrapy合同
我当前的示例:我有一种方法,称为parse_product
,它提取页面上的信息,但我需要为另一页面中的同一产品提取更多数据,因此我yield
在此结尾处有一个新请求方法来创建新的请求,并让新的回调提取这些字段并返回该项目。
问题是,如果我为第二种方法编写合同,它将失败,因为它没有元属性(包含大多数字段的项目)。如果我为第一个方法编写合同,我无法检查它是否返回字段,因为它返回一个新的请求,而不是该项目。
def parse_product(self, response):
il = ItemLoader(item=ProductItem(), response=response)
# populate the item in here
# yield the new request sending the ItemLoader to another callback
yield scrapy.Request(new_url, callback=self.parse_images, meta={'item': il})
def parse_images(self, response):
"""
@url http://foo.bar
@returns items 1 1
@scrapes field1 field2 field3
"""
il = response.request.meta['item']
# extract the new fields and add them to the item in here
yield il.load_item()
在这个例子中,我把合同中的第二个方法,但它给了我一个KeyError
例外的response.request.meta['item']
,还等领域field1
和field2
在第一种方法填充。
希望它很清楚。
这不完全是我正在寻找的答案,但它确实帮了我很多,也许比实际的答案(如果存在)更多。谢谢。 –