Item Pipelines
当Item在Spider中被收集之后,它将会被传递到Item Pipeline
每个Item Pipeline组件接收到Item,定义一些操作行为,比如决定此Item是丢弃而存储。
以下是item pipeline的一些典型应用:
- 验证爬取的数据(检查item包含某些字段,比如说name字段)
- 查重(并丢弃)
- 将爬取结果保存到文件或者数据库中
编写item pipeline
编写item pipeline很简单,item pipiline组件是一个独立的Python类,必须实现process_item方法:
process_item(self, item, spider)
当Item在Spider中被收集之后,都需要调用该方法
参数:
item - 爬取的结构化数据spider – 爬取该item的spider
open_spider(self, spider)
当spider被开启时,这个方法被调用。
参数:
spider – 被开启的spider
close_spider(spider)
当spider被关闭时,这个方法被调用
参数:
spider – 被关闭的spider
将item写入JSON文件
以下pipeline将所有爬取到的item,存储到一个独立地items.json 文件,每行包含一个序列化为'JSON'格式的'item':
import jsonclass JsonWriterPipeline(object):def __init__(self):self.file = open('items.json', 'wb')def process_item(self, item, spider):line = json.dumps(dict(item),ensure_ascii=False) + "\n"self.file.write(line)return item
启用一个Item Pipeline组件
为了启用Item Pipeline组件,必须将它的类添加到 settings.py文件ITEM_PIPELINES 配置,就像下面这个例子:
ITEM_PIPELINES = {#'tutorial.pipelines.PricePipeline': 300,'tutorial.pipelines.JsonWriterPipeline': 800,}
分配给每个类的整型值,确定了他们运行的顺序,item按数字从低到高的顺序,通过pipeline,通常将这些数字定义在0-1000范围内。
在这里优化:
以下pipeline将所有爬取到的item,存储到一个独立地items.json 文件,每行包含一个序列化为'JSON'格式的'item':
import jsonimport codecsclass JsonWriterPipeline(object):def __init__(self):self.file = codecs.open('items.json', 'w', encoding='utf-8')def process_item(self, item, spider):line = json.dumps(dict(item), ensure_ascii=False) + "\n"self.file.write(line)return itemdef spider_closed(self, spider):self.file.close()
针对spider里面的utf-8编码格式去掉.encode('utf-8')
item = RecruitItem()item['name']=name.encode('utf-8')item['detailLink']=detailLink.encode('utf-8')item['catalog']=catalog.encode('utf-8')item['recruitNumber']=recruitNumber.encode('utf-8')item['workLocation']=workLocation.encode('utf-8')item['publishTime']=publishTime.encode('utf-8')
将item写入MongoDB
from_crawler(cls, crawler)
如果使用,这类方法被调用创建爬虫管道实例。必须返回管道的一个新实例。crawler提供存取所有Scrapy核心组件配置和信号管理器;对于pipelines这是一种访问配置和信号管理器 的方式。
参数: crawler (Crawler object) – crawler that uses this pipeline
在这个例子中,我们将使用pymongo将Item写到MongoDB。MongoDB的地址和数据库名称在Scrapy setttings.py配置文件中;
这个例子主要是说明如何使用from_crawler()方法
import pymongoclass MongoPipeline(object):collection_name = 'scrapy_items'def __init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddef from_crawler(cls, crawler):return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DATABASE', 'items'))def open_spider(self, spider):self.client = pymongo.MongoClient(self.mongo_uri)self.db = self.client[self.mongo_db]def close_spider(self, spider):self.client.close()def process_item(self, item, spider):self.db[self.collection_name].insert(dict(item))return item