scrapy连接MongoDB
import pymongo
class TaochePipeline(object):
def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db
#MongoPipeline(mongo_uri,mongo_db)
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URL'),
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):
# print(item)
# collection_name = item.__class__.__name__
# self.db[collection_name].insert(dict(item))
crumbs = item['crumbs']
novel_url = item['href']
# #True:如果url存在就更新,不存在就插入
self.db[crumbs].update({'href': novel_url}, {'$set': item}, True)
return item
配置文件
MONGO_URL = 'localhost'
MONGO_DATABASE = 'taoche'