Python:Scrapy框架中Item Pipeline组件使用详解
Item Pipeline简介 Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清晰、验证和存储数据。 Item管道通常执行的过程有 清理HTML数据 编写自己的Item Pipeline 编写item管道其实是很容易的。 process_item(item,spider) 每一个item管道组件都会调用该方法,并且必须返回一个item对象实例或raise DropItem异常。 open_spider(spider) 当spider执行的时候将调用该方法 close_spider(spider) 当spider关闭的时候将调用该方法 代码如下: from scrapy.exceptions import DropItem class PricePipeline(object): vat_factor = 1.15 def process_item(self,item,spider): if item['price']: if item['price_excludes_vat']: item['price'] = item['price'] * self.vat_factor return item else: raise DropItem("Missing price in %s" % item) 注:VAT:ValueAddedTax(增值税) 以上代码可以过滤那些没有价格的产品,并且对那些不包括增值税产品的价格进行调整 将抓取的items以json格式保存到文件中 从spider抓取到的items将被序列化为json格式,并且以每行一个item的形式被写入到items.jl文件中 代码: import json class JsonWriterPipeline(object): def __init__(self): self.file = open('items.jl','wb') def process_item(self,spider): line = json.dumps(dict(item)) + "n" self.file.write(line) return item 注:JsonWriterPipeline的目的是介绍如何编写项目管道。如果想要保存抓取的items到json文件中,推荐使用Feedexports 删除重复项 假设在spider中提取到的item有重复的id,那么我们就可以在process_item函数中进行过滤 如: from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.ids_seen = set() def process_item(self,spider): if item['id'] in self.ids_seen: raise DropItem("Duplicate item found: %s" % item) else: self.ids_seen.add(item['id']) return item 激活ItemPipeline组件 在settings.py文件中,往ITEM_PIPELINES中添加项目管道的类名,就可以激活项目管道组件 如: ITEM_PIPELINES = { 'myproject.pipeline.PricePipeline': 300,'myproject.pipeline.JsonWriterPipeline': 800,} The integer values you assign to classes in this setting determine the order they run in- items go through pipelines from order number low to high 整数值通常设置在0-1000之间 总结 以上就是本文关于Python:Scrapy框架中Item Pipeline组件使用详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站: Python使用Scrapy保存控制台信息到文本解析 Python爬虫实例爬取网站搞笑段子 Python爬虫获取整个站点中的所有外部链接代码示例 如有不足之处,欢迎留言指出。感谢朋友们对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |