【问题标题】:Scrapy: yield form request prints none?Scrapy:产量表单请求不打印?
【发布时间】:2016-12-16 08:21:37
【问题描述】:

我正在写一个蜘蛛来报废网站:

第一个 url www.parenturl.com 调用 parse 函数,从那里我提取了 url www.childurl.com,我有一个回调到 parse2 函数并返回 dict。

问题 1)我需要将 dict 值与我在解析函数中从父 url 中提取的其他 7 个值一起存储在 mysql 数据库中吗? (response_url 不打印)

def parse(self, response):
    for i in range(0,2):
        url = response.xpath('//*[@id="response"]').extract()
        response_url=yield SplashFormRequest(url,method='GET',callback=self.parse2)
        print response_url # prints None

def parse2(self, response):
    dict = {'url': response.url}
    return dict

【问题讨论】:

    标签: python web scrapy scrapy-spider scrapy-splash


    【解决方案1】:

    由于scrapy的asynchronous nature,无法保证将第二个回调的结果存储在蜘蛛对象上然后打印它。相反,您可以尝试passing additional data to callback functions,例如:

    def parse(self, response):
        for i in range(0, 2):
            item = ...  # extract some information
            url = ...  # construct URL
            yield SplashFormRequest(url, callback=self.parse2, meta={'item': item})
    
    def parse2(self, response):
        item = response.meta['item']  # get data from previous parsing method
        item.update({'key': 'value'})  # add more information
        print item  # do something with the "complete" item
        return item
    

    【讨论】:

      【解决方案2】:

      您不能将 yield 调用等同于变量,因为它的作用类似于返回调用。

      尝试删除它

      def parse(self, response):
          self.results = []
          for i in range(0,2):
              url = response.xpath('//*[@id="response"]').extract()
              request = SplashFormRequest(url,method='GET',callback=self.parse2)
              yield request
          print self.results
      
      def parse2(self, response):
          # print response here !
          dict = {'url': response.url}
          self.results.append(dict)
      

      【讨论】:

      • 好的,但是我在哪里可以捕获和打印从 parse2 函数返回的 dict?
      • 将其存储在 parse2 函数中。即不要退货
      • 但是我在解析函数中有 7 个值要插入到我从父 url 中提取的 dB 中。
      • 不确定您的意思。你指的是你的 for 循环吗?
      • 我在解析函数中提取其他值...不包括该代码..
      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2016-11-18
      相关资源
      最近更新 更多