【发布时间】: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'
问题:
我想为不同的蜘蛛设置不同的集合名称,怎么做?
【问题讨论】: