Skip to main content
 首页 » 编程设计

python之Scrapy之在管道中创建额外的项目

2024年10月01日8zhenyulu

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

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

它们以正确的顺序执行。

1.) 第一个管道是一个修改器。

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

数据正确提交到数据库。

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

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

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

但是,我不能多次返回。我也不想创建从管道 1 开始的附加项。

许多人提前提供帮助。

请您参考如下方法:

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

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

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