scrapy 使用mongo连接数据库的三种方法

scrapy 使用mongoDB的三种方法

   完成连接数据库的工作,需要在系统中完成至少下面两步;
1.在系统中安装MongoDB(官网下载链接:https://www.mongodb.com/try/download/community,按照本机系统版本安装即可,32bit windows系统 下载i386的版本即可安装) ;
2.在python环境中安装pymongo包(官网链接:https://pypi.org/project/pymongo/

   下面来则是三种连接方法:
(1)硬编码

pipelines.py
from scrapy.item import Item
import pymongo #提前用pip安装
class MongoDBPipeline(object):
	DB_URI = 'mongodb://localhost:27017/' #直接将DB_URI,DB_NAME 写下具体的内容,随后在setting中配置
	DB_NAME = 'scrapy_data'
	def open_spider(self, spider):
		self.client = pymongo.MongoClient(self.DB_URI)
		self.db = self.client[self.DB_NAME]
	def close_spider(self, spider):
		self.client.close()
		...

   接下来测试MongoDBPipeline,在配置文件settings.py中启用
MongoDBPipeline:

setting.py
ITEM_PIPELINES = {
	'example.pipelines.MongoDBPipeline': 300, 
}

(2) 利用from_crawler方法传入DB_URI,DB_NAME。
   在from_crawler方法中,读取配置文件中的MONGO_DB_URI和MONGO_DB_NAME(不存在使用默认值),赋给cls的属性,即MongoDBPipeline类属性。

pipelines.py
class MongoDBPipeline1(object):
    @classmethod
    def from_crawler(cls, crawler):
        cls.DB_URI = crawler.settings.get('MONGODB_URI', 'mongodb://localhost:27017/')
        cls.DB_NAME = crawler.settings.get('MONGODB_NAME', 'scrapy_data1')
        return cls()

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

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

   接下来测试MongoDBPipeline,在配置文件settings.py中启用
MongoDBPipeline:

setting.py
ITEM_PIPELINES = {
   'example1.pipelines.MongoDBPipeline1' : 300, # setting.py 中配置相关的MongoDBPipeline1类
}

(3)直接在setting配置MONGO_DB_URI ,MONGO_DB_NAME 。编写的数据处理文件中获得配置信息,来使用,注意即使利用from_crawler方法传入DB_URI,DB_NAME,也会根据setting中的定义进行操作,

setting.py
MONGO_DB_URI = 'mongodb://localhost:27017/'
MONGO_DB_NAME = 'scrapy_data2'
ITEM_PIPELINES = {
   'example1.pipelines.MongoDBPipeline2' : 300,
}

导入方法

pipelines.py

from scrapy.utils.project import get_project_settings
class MongoDBPipeline2(object):
    def __init__(self):
        setting=get_project_settings()
        self.DB_URI = setting['MONGODB_URI']
        self.DB_NAME = setting['MONGODB_NAME']
    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.DB_URI)
        self.db = self.client[self.DB_NAME]

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

    本文根据学习得《精通Scrapy网络爬虫》(刘硕著)相关内容,自己跑相关代码,个人总结,仅做参考和笔记复习使用。如有疑问,欢迎讨论或批评指正;如有转发 ,注明本篇链接地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值