Skip to main content
 首页 » 编程设计

python之在 scrapy 的管道中注入(inject)参数

2025年02月15日9linjiqin

我有一个自定义管道,其中包含一些我需要在构造函数中注入(inject)的参数,例如:

class MyPipeline(object): 
    def __init__(self, some_argument): 
        self.some_argument = some_argument 
... 

脚本(我们称之为 run_crawler.py)是我开始抓取过程的地方:

process = CrawlerProcess(get_project_settings()) 
 
process.crawl(SomeCrawler) 
process.crawl(AnotherCrawler) 
... 
process.start() 

在 settings.py 中:

ITEM_PIPELINES = { 
    'crawler.pipelines.SomePipeline': 100, 
    'crawler.pipelines.MyPipeline': 300 
} 

我想这是一个愚蠢的问题,但我一直无法在 docs 中找到如何使用自定义参数实例化 MyPipeline。有人能给我指出正确的方向吗?

特别是,我不知道应该如何(或者我是否应该)修改 run_crawler.py 来实例化 MyPipeline 的自定义参数,我猜它应该是这样的:

process = CrawlerProcess(get_project_settings()) 
 
process.crawl(SomeCrawler) 
process.crawl(AnotherCrawler) 
... 
some_argument = ... # instantiate my custom argument 
# this is made up, it's what i've been unable to find how to do properly 
my_pipeline = MyPipeline(some_argument) 
process.pipelines.append(my_pipeline, ...) 
 
process.start() 

请您参考如下方法:

您可以使用 scrapy from_crawler 方法。 scrapy 文档有一个很好的 description和 example :

class MongoPipeline(object): 
 
    collection_name = 'scrapy_items' 
 
    def __init__(self, mongo_uri, mongo_db): 
        self.mongo_uri = mongo_uri 
        self.mongo_db = mongo_db 
 
    @classmethod 
    def from_crawler(cls, crawler): 
        return cls( 
            mongo_uri=crawler.settings.get('MONGO_URI'), 
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') 
        ) 

“如果存在,则调用此类方法以从 Crawler 创建管道实例。它必须返回管道的新实例。”

通过这种方式,您可以根据爬虫或蜘蛛设置创建新的管道实例。