Skip to main content
 首页 » 编程设计

python之Scrapy 项目管道并行或顺序执行 process_item

2025年02月15日11exmyth

我正在开发一个 scrapy 蜘蛛,它成功地产生了一些元素。这些项目应该使用 pymysql 插入到数据库中。因为数据是相关的,所以我必须为每个项目执行一些插入语句。 我想在每次完整插入后调用 connection.commit() 以确保发生的错误不会导致我的数据库中出现不一致的条目。

我目前想知道 scrapy 是否会为多个项目并行调用 process_item 或一个接一个地顺序调用。如果是后者,我可以简单地使用以下方法:

def process_item(self, item, spider): 
    # execute insert statements 
    connection.commit() 

如果scrapy同时执行多个process_item调用,最后调用commit()可能会调用另一个item完全插入。

documentation for item pipelines状态:

After an item has been scraped by a spider, it is sent to the Item Pipeline which processes it through several components that are executed sequentially.

但我不太确定这是否意味着 process_item 永远不会并行执行,或者只是不同的管道总是一个接一个地执行(例如删除重复 ->改变一些东西-> 数据库插入)。


我认为 process_item 将按顺序执行,因为文档显示了以下示例:

class DuplicatesPipeline(object): 
 
def __init__(self): 
    self.ids_seen = set() 
 
def process_item(self, item, spider): 
    if item['id'] in self.ids_seen: 
        raise DropItem("Duplicate item found: %s" % item) 
    else: 
        self.ids_seen.add(item['id']) 
        return item 

这段代码中,没有涉及将id添加到ids_seen中的同步,但是我不知道这个例子是否简化了,因为它只是演示了如何使用管道。

请您参考如下方法:

CONCURRENT_ITEMS 的文档设置指定并行处理项目(至少在单个响应中)。我认为将其设置为 1 可能对您的情况有所帮助。

我不是Scrapy这部分的专家,但我相信this is where it happens .