我试图抓取数据并保存在一个mongo database.There中,这是两个文件(whole.py和admissionReq.py),用于抓取数据,但这两个文件都保存在一个集合“课程”中。
这是我的档案:
whole.py: https://pastebin.com/ZpSER6wr
admissionReq: https://pastebin.com/5CQ7qRBM
settings.py: https://pastebin.com/dnPNqveq
pipelines: https://pastebin.com/YRfWiFhF
items: https://pastebin.com/1FGprEJj我想要
我哪里出错了?
发布于 2018-03-23 09:48:37
似乎您正在从scrapy.conf.settings传递管道中的集合名称--这对于所有蜘蛛来说都是一样的,这意味着通过管道处理的所有项都将插入在scrapy.conf.settings中命名的同一个集合中。
相反,您可以做的是在蜘蛛的设置中指定特定蜘蛛的集合名称,如下所示:
class Spider(scrapy.Spider):
name = 'foo'
custom_settings = {
'COLLECTION_NAME' : 'foo'
}然后检索mongo管道中的设置如下:
import pymongo
class MongoPipeline(object):
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')
)
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[spider.settings.get('COLLECTION_NAME')].insert_one(dict(item))
return item注意,在process_item(self, item, spider中,我从spider.settings.get('COLLECTION_NAME')检索COLLECTION_NAME参数
https://stackoverflow.com/questions/49373693
复制相似问题