scrapy插入mongodb不起作用

时间:2017-05-31 08:12:01

标签: python mongodb scrapy database

当我试图将我的刮擦结果保存到mongodb时,我遇到了问题。在终端上没有显示错误,但数据没有保存到mongodb。

pipline.py

class MongoDBPipeline(object):

    collection_name = 'lalaland'

    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 = 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(dict(item))
        logging.debug("Added to mongo")
        return item

settings.py

ITEM_PIPELINES = {
    'lalaland.pipelines.MongoDBPipeline':300
}

MONGO_URI = 'mongodb://localhost:27017'
MONGODB_DATABASE = 'lala_db'

item.py

class InforItem(Item):
    link = Field()
    caption = Field()

spider.py

item = InfoItem()
        item['link'] = response.url
        item['body'] = ' '.join(response.xpath("//li[@class='_cak6a'][1]/h1/span//text()").extract())
yield item

0 个答案:

没有答案