2017-07-30 86 views
1

我試圖通過URL的從傳遞給scrapy請求回調返回一個列表進行迭代,但我發現了以下錯誤:Scrapy - 類型錯誤:「請求」對象不是可迭代

TypeError: 'Request' object is not iterable 

以下作品。我可以看到所有的提取的URL的洪水終端:

import scrapy 

class PLSpider(scrapy.Spider): 
    name = 'pl' 
    start_urls = [ 'https://example.com' ] 

    def genres(self, resp): 
     for genre in resp.css('div.sub-menus a'): 
      yield { 
       'genre': genre.css('::text').extract_first(), 
       'url': genre.css('::attr(href)').extract_first() 
      } 

    def extractSamplePackURLs(self, resp): 
     return { 
      'packs': resp.css('h4.product-title a::attr(href)').extract() 
     } 

    def extractPackData(self, resp): 
     return { 
      'title': resp.css('h1.product-title::text'), 
      'description': resp.css('div.single-product-description p').extract_first() 
     } 

    def parse(self, resp): 
     for genre in self.genres(resp): 
      samplePacks = scrapy.Request(genre['url'], callback=self.extractSamplePackURLs) 
      yield samplePacks 

但是如果我更換yield samplePacks行:

def parse(self, resp): 
     for genre in self.genres(resp): 
      samplePacks = scrapy.Request(genre['url'], callback=self.extractSamplePackURLs) 
      for pack in samplePacks: 
       yield pack 

...我得到我上面張貼的錯誤。

爲什麼會這樣以及如何循環返回的回調值?

+0

您在回調函數中生成樣本包數據......產生Request對象的所有操作都是添加另一個頁面以用相關回調進行刮取 - 回調應該返回(不返回)數據... –

+0

samplePacks沒有定義__iter __(),所以它不能被迭代? –

+0

我想我可能會在這裏感到困惑。我以爲'Request'會從回調中返回列表? – BugHunterUK

回答

2

產生Requestscrapy.Spider中的對象回調函數只會告訴Scrapy框架排入HTTP請求。它產生HTTP請求對象,就是這樣。它不會立即下載它們。或者給予控制權直到他們被下載,即。在收益率之後,你仍然沒有結果。對象不是承諾,期貨,延期。 Scrapy的設計與各種異步框架不同。

這些Request對象將最終由框架的下載器處理,並且每個HTTP請求的響應正文將傳遞給關聯的回調。 這是Scrapy異步編程模式的基礎。

如果您想要做更類似「類似程序」的事情,其中​​yield request(...)在下次有控制權時獲得HTTP響應,您可以查看https://github.com/rmax/scrapy-inline-requests/

相關問題