[英]yield scrapy.Request does not invoke parse function on each iteration
[英]Scrapy yield a Request, parse in the callback, but use the info in the original function
所以我試圖在scrapy中測試一些網頁,我的想法是向滿足條件的URLS產生一個請求,計算頁面上某些項目的數量,然后在原始條件內返回True/False,具體取決於.. .
這是一些代碼來顯示我的意思:
def filter_categories:
if condition:
test = yield Request(url=link, callback = self.test_page, dont_filter=True)
return (test, None)
def test_page(self, link):
... parse the response...
return True/False depending
我試過在請求中傳遞一個項目,但無論在調用 test_page 之前觸發了什么返回行......
所以我想我的問題變成了有沒有辦法以同步方式將數據傳遞回 filter_categories 方法,以便我可以使用 test_page 的結果來返回我的測試是否滿足?
也歡迎任何其他想法。
看看inline_requests包,它應該可以讓你實現這一點。
其他解決方案是不堅持從原始方法(在您的情況下為filter_categories
)返回結果,而是使用請求的meta
屬性請求鏈接並從鏈中的最后一個解析方法(在您的情況下為test_page
)返回結果。
如果我理解你是正確的:你想將yield scrapy.Request
給具有True
條件的URL。 我說得對嗎? 這里有一些例子:
def parse(self, response):
if self.test_page(response):
item = Item()
item['url'] = 'xpath or css'
yield item
if condition:
yield Request(url=new_link, callback = self.parse, dont_filter=True)
def test_page(self, link):
... parse the response...
return True/False depending
如果您提供更多信息,我會嘗試提供更多幫助。
這是我代碼的一部分
def parse(self, response):
if 'tag' in response.url:
return self.parse_tag(response)
if 'company' in response.url:
return self.parse_company(response)
def parse_tag(self, response):
try:
news_list = response.xpath("..//div[contains(@class, 'block block-thumb ')]")
company = response.meta['company']
for i in news_list:
item = Item()
item['date'] = i.xpath("./div/div/time/@datetime").extract_first()
item['title'] = i.xpath("./div/h2/a/text()").extract_first()
item['description'] = i.xpath("./div/p//text()").extract_first()
item['url'] = i.xpath("./div/h2/a/@href").extract_first()
item.update(self.get_common_items(company))
item['post_id'] = response.meta['post_id']
if item['title']:
yield scrapy.Request(item['url'], callback=self.parse_tags, meta={'item': item})
has_next = response.xpath("//div[contains(@class, 'river-nav')]//li[contains(@class, 'next')]/a/@href").extract_first()
if has_next:
next_url = 'https://example.com' + has_next + '/'
yield scrapy.Request(next_url, callback=self.parse_tag,
meta=response.meta)
def parse_tags(self, response):
item = response.meta['item']
item['tags'] = response.xpath(".//div[@class='accordion recirc-accordion']//ul//li[not(contains(@class, 'active'))]//a/text()").extract()
yield item
你可以使用:
response.meta
response.body
函數的收益
重構你的蜘蛛
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.