pipelines的使用
前面介绍了我们使用
scrapy框架爬取数据的时候,要提取到数据库或者写入本地文件中,我们正常的方式会先定义Item约束需要下载的字段,然后再Spider中使用,当Spider下载的数据,会交给pipelines中处理,写入到本地文件中或者数据库中(pipelines更多的功能主要是写入数据)
一、关于pipelines中主要的方法
1、
process_item(self, item, spider):必须写的方法- 1.
Item:Spider爬虫中yield出来的item对象 - 2.
spider:是Spider对象,如果一个工程中有多个爬虫就需要使用spider.name来判断当前的爬虫
- 1.
2、
open_spider(self, spider):代表开启爬虫的时候执行的方法(常用于开启数据库连接,开启文件写入)- 3、
close_spider(self, spider):代表关闭爬虫的时候执行的方法(常用于关闭数据库,关闭文件写入) - 4、
from_crawler(cls, crawler):定义一个类方法(主要使用Scrapy的核心组件,比如settings、singals)
二、使用pipelines将数据写入mongodb中
1、在
settings.py中设置mongodb数据库连接# 配置mongodb数据库 MONGO_URI = 'localhost' MONGO_DATABASE = 'py_test'2、书写
pipelinesimport pymongo class MongoPipeline(object): # 定义表名 collection_name = 'jobb_item' def __init__(self, mongo_url, mongo_db): self.mongo_url = mongo_url self.mongo_db = mongo_db self.client = None self.db = None @classmethod def from_crawler(cls, crawler): return cls( mongo_url=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'item') ) def open_spider(self, spider): """ 打开爬虫的时候 :param spider: :return: """ self.client = pymongo.MongoClient(self.mongo_url) self.db = self.client[self.mongo_db] def close_spider(self, spider): """ 爬虫关闭的时候 :param spider: :return: """ self.client.close() def process_item(self, item, spider): """ 主要处理数据 :param item: :param spider: :return: """ if spider.name == 'blog': self.db[self.collection_name].insert(dict(item)) return item3、在
settings.py中注册自己写的pipelines类ITEM_PIPELINES = { 'jobbloe.pipelines.MongoPipeline': 300, }