scrapy自定义pipeline类实现将采集数据保存到mongodb的方法

yipeiwu_com6年前Python基础

本文实例讲述了scrapy自定义pipeline类实现将采集数据保存到mongodb的方法。分享给大家供大家参考。具体如下:

# Standard Python library imports
# 3rd party modules
import pymongo
from scrapy import log
from scrapy.conf import settings
from scrapy.exceptions import DropItem
class MongoDBPipeline(object):
  def __init__(self):
    self.server = settings['MONGODB_SERVER']
    self.port = settings['MONGODB_PORT']
    self.db = settings['MONGODB_DB']
    self.col = settings['MONGODB_COLLECTION']
    connection = pymongo.Connection(self.server, self.port)
    db = connection[self.db]
    self.collection = db[self.col]
  def process_item(self, item, spider):
    err_msg = ''
    for field, data in item.items():
      if not data:
        err_msg += 'Missing %s of poem from %s\n' % (field, item['url'])
    if err_msg:
      raise DropItem(err_msg)
    self.collection.insert(dict(item))
    log.msg('Item written to MongoDB database %s/%s' % (self.db, self.col),
        level=log.DEBUG, spider=spider)
    return item

希望本文所述对大家的python程序设计有所帮助。

相关文章

Python设置在shell脚本中自动补全功能的方法

本篇博客将会简短的介绍,如何在ubuntu中设置python自动补全功能。 需求:由于python中的内建函数较多,我们在百纳乘时,可能记不清函数的名字,同时自动补全功能,加快了我们开发...

Numpy之reshape()使用详解

Numpy之reshape()使用详解

如下所示: Numpy中reshape的使用方法为:numpy.reshape(a, newshape, order='C') 参数详解: 1.a: type:array_like(伪数...

Python超越函数积分运算以及绘图实现代码

Python超越函数积分运算以及绘图实现代码

编译环境:ubuntu17.04 Python3.5 所需库:numpy、scipy、matplotlib 下面是理想平面的辐射强度计算(课程大作业~~~) 1、超越函数积分运算 d...

python实现的简单抽奖系统实例

本文实例讲述了python实现的简单抽奖系统。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python #coding=utf-8 from Tkinte...

python3.4下django集成使用xadmin后台的方法

python3.4下django集成使用xadmin后台的方法

环境:window7 x64、python3.4、django1.10 一、pip install xadmin安装报错 1、使用pip install xadmin命令安装可能报如下错...