Scrapy custom Pipeline class implements the method of saving the collected data to MongoDB

Source: Internet
Author: User
The example in this paper describes how the Scrapy custom pipeline class implements the method of saving the collected data to MongoDB. Share to everyone for your reference. Specific as follows:

# Standard Python Library imports# 3rd party modulesimport pymongofrom scrapy import logfrom scrapy.conf import SETTINGSFR Om scrapy.exceptions Import dropitemclass 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 + = ' Missin G%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

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.