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

yipeiwu_com5年前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绘制3维正态分布图的方法

使用python绘制3维正态分布图的方法

今天使用python画了几个好玩的3D展示图,现在分享给大家。 先贴上图片 使用的python工具包为: from matplotlib import pyplot as pl...

如何使用Python进行OCR识别图片中的文字

朋友需要一个工具,将图片中的文字提取出来。我帮他在网上找了一些OCR的应用,都不好用。所以准备自己研究,写一个Web APP供他使用。 OCR1,全称Optical character...

Python 实现文件读写、坐标寻址、查找替换功能

Python 实现文件读写、坐标寻址、查找替换功能

读文件 打开文件(文件需要存在) #打开文件 f = open("data.txt","r") #设置文件对象 print(f)#文件句柄 f.close() #关闭文件 #为了方...

python点击鼠标获取坐标(Graphics)

python点击鼠标获取坐标(Graphics)

使用Python进行图像编程,要使用到Graphics库。下面列举出较常用的代码 from graphics import * #设置画布窗口名和尺寸 win = Graph...

Python中for循环和while循环的基本使用方法

while循环: while expression: suite_to_repeat while 条件:    语句块 不需要括号哦! >&g...