本文共 2946 字,大约阅读时间需要 9 分钟。
给IT入门加星标,提升编程技能
当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 item def 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
这是一种访问配置和信号管理器 的方式。
在这个例子中,我们将使用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_uri self.mongo_db = mongo_db @classmethod def 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
piaosanlang https://piaosanlang.gitbooks.io/spiders/content/
- EOF -
推荐阅读 点击标题可跳转
都来到这了,拜托拜托点个赞
转载地址:https://cpython.blog.csdn.net/article/details/112419607 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!