【问题标题】:Scrapy: How to get return values from Scrapy.Request?Scrapy:如何从 Scrapy.Request 中获取返回值?
【发布时间】:2020-08-19 01:48:58
【问题描述】:

我目前正试图弄清楚如何从一个 scrapy 请求中获取返回值。第一个 sn-p 显示了我执行请求的方式。在解析函数(2nd sn-p)中,我提取了一些我想用两个列表返回的值。我的问题是:如何在第一个 sn-p 中的 yield 语句之后获得这两个值?

        while i < pages:
        # default link is combined with the specific page number
        url = link+str(i)
        yield scrapy.Request(url=url, callback=self.parse)
        i = i+1

第二个sn-p:

    def parse(self, response):

    # here the code is filling x_array and y_array with values

    return x_array, y_array

非常感谢您的帮助!!

【问题讨论】:

    标签: python web-scraping scrapy request


    【解决方案1】:

    来自 Scrapy 的请求不仅可以返回值,还可以填充 Items(类似字典的结构),您可以在 Item Pipelines 中进一步处理。 在您的情况下,将其添加到您的 item.py 文件中就足够了:

    from scrapy.item import Item, Field
    
    class TestItem(Item):
        x_array = Field()
        y_array = Field()
    

    在你的蜘蛛中,你填充项目并像这样输出它:

    from ..items import TestItem
    def parse(self, response):
        x_array = ['test1', 'test2']
        y_array = ['test3']
        item = TestItem()
        item['x_array'] = x_array
        item['y_array'] = y_array
        yield item
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 2015-09-30
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多