【问题标题】:Scrapy : How to write items of different spiders to different MongoDB collections?Scrapy:如何将不同蜘蛛的项目写入不同的 MongoDB 集合?
【发布时间】:2018-02-11 06:58:19
【问题描述】:

如何将不同spider的item写入不同的MongoDB集合?

项目的结构是这样的:

myproject/
    scrapy.cfg
    myproject/
        __init__.py
        items.py
        pipelines.py
        settings.py
        spiders/
            __init__.py
            spider1.py
            spider2.py
            ...

根据文档,https://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-mongodb

在本例中,我们将使用 pymongo 将项目写入 MongoDB。 MongoDB地址和数据库名称在Scrapy设置中指定; MongoDB 集合以项目类命名。

还有一段来自文档的代码:

import pymongo

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

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        self.db[self.collection_name].insert_one(dict(item))
        return item

在上面的代码中,集合名称是:

collection_name = 'scrapy_items'

问题:

我想为不同的蜘蛛设置不同的集合名称,怎么做?

【问题讨论】:

    标签: mongodb scrapy


    【解决方案1】:

    在爬虫类中插入您想要的名称,如下所示

    class Spider1(scrapy.Spider):
        collection_name = 'scrapy_items_my_crawler'
    

    然后改变

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
    

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
        if hasattr(spider, 'collection_name'):
           self.collection_name = spider.collection_name
    

    如果您的蜘蛛定义了collection_name,这将根据您的蜘蛛覆盖collection_name。如果没有,那么它将使用默认的scrapy_items

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 2012-01-12
      • 2016-03-23
      • 2013-08-05
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      相关资源
      最近更新 更多