2017-09-02 76 views
1

如何将不同的蜘蛛项目写入不同的MongoDB集合?Scrapy:如何将不同蜘蛛的项目写入不同的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集合以item类命名。

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

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' 

Quesition:

我想设置不同的蜘蛛集合名称,如何做到这一点?

回答

2

插入您要喜欢你的爬虫类下面的名字

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,如果你的蜘蛛定义了一个。如果不是那么它将使用默认的scrapy_items