【问题标题】:Scrapy - Create Additional Items In PipelineScrapy - 在管道中创建其他项目
【发布时间】:2017-05-31 16:31:38
【问题描述】:

所以我目前有 2 条管道,它们的顺序如下。

ITEM_PIPELINES = {
    'myproject.pipelines.mutatorPipeline': 300,
    'myproject.pipelines.submitDatabasePipeline': 800,
}

它们以正确的顺序执行。

1.) 第一个管道是一个 mutator。

2.) 第二个是将信息提交到数据库。

数据正确提交到数据库。

我的问题是,有时当数据到达我的mutator pipeline 时,我想创建“其他”项目以传递到我的第二个管道。

目前(没有突变)它看起来像这样:

def process_item(self, item, spider):
            #Mutate the item
            return item

但我不能,return 不止一次。我也不想创建从管道 1 开始的附加项目。

提前提供许多帮助。

【问题讨论】:

    标签: python web-scraping scrapy


    【解决方案1】:

    快速查看文档,您可能可以创建scrapy.item.Item 的子类,这有点像链表。

    没有接触过像这样的东西可以做到这一点。它可能需要一些修改,但应该足以让您入门。

    class Myitem(Item):
        my_field = scrapy.Field()
    
        def __init__(self):
            self.next = None
            super(Myitem,self).__init__()
    

    现在您的流程项目可以创建多个项目并将它们链接起来。

    def process_item(self, item, spider):
            # Mutate the item, get additional my_value
            item.next = MyItem()
            item.next['my_field'] = my_value
            return item
    

    现在您可以在您的数据库管道中处理每个项目。

    def process_item(self, item, ...):
        current = item
        while current:
            # process current
            current = item.next
    

    【讨论】:

    • 总是让项目成为一个列表然后循环它。好主意!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多