欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python爬虫之Scrapy数据保存MongoDB

程序员文章站 2022-05-06 18:47:15
...

Python爬虫之Scrapy数据保存MongoDB

首先在Pipelines.py中创建一个类:

class MongoPipline(object):
    def __init__(self, mongo_url, mongo_db):
        self.mongo_url = mongo_url
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_url=crawler.settings.get('MONGO_URL'),
            mongo_db=crawler.settings.get('MONGO_DB')
        )

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

    def process_item(self, item, spider):
        # name =item.__class__.__name__
        self.db['Article'].insert(dict(item))
        return item

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

在Settings.py文件中加入MongoDB的地址和数据库如:

MONGO_URL = 'localhost'
MONGO_DB = 'Article'