在斯帕利的pipelin中注入参数

2024-09-28 03:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

脚本(我们称之为运行_爬虫.py)从我开始爬行的地方开始是:

^{pr2}$

在设置.py公司名称:

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

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

特别是,我不知道应该如何(或者是否应该)修改run_爬虫.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()

Tags: to实例pyself参数pipelinemysome
1条回答
网友
1楼 · 发布于 2024-09-28 03:20:05

您可以使用scrapyfrom_crawler方法。 废文档有一个好的description和{a2}:

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')
        )

如果存在,则调用此classmethod从爬虫程序创建管道实例。它必须返回管道的新实例。

这样,您就可以根据爬虫程序或爬行器设置创建管道的新实例。在

相关问题 更多 >

    热门问题