网络编程
位置:首页>> 网络编程>> Python编程>> Python:Scrapy框架中Item Pipeline组件使用详解

Python:Scrapy框架中Item Pipeline组件使用详解

作者:曾是土木人  发布时间:2021-04-18 22:22:47 

标签:python,scrapy,管道组件

Item Pipeline简介

Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清晰、验证和存储数据。
当页面被蜘蛛解析后,将被发送到Item管道,并经过几个特定的次序处理数据。
每个Item管道的组件都是有一个简单的方法组成的Python类。
他们获取了Item并执行他们的方法,同时他们还需要确定的是是否需要在Item管道中继续执行下一步或是直接丢弃掉不处理。

Item管道通常执行的过程有

清理HTML数据
验证解析到的数据(检查Item是否包含必要的字段)
检查是否是重复数据(如果重复就删除)
将解析到的数据存储到数据库中

编写自己的Item Pipeline

编写item管道其实是很容易的。
每个Item管道的组件都是由一个简单的方法组成的Python类:

process_item(item, spider)

每一个item管道组件都会调用该方法,并且必须返回一个item对象实例或raise DropItem异常。
被丢掉的item将不会在管道组件进行执行
此外,我们也可以在类中实现以下方法

open_spider(spider)

当spider执行的时候将调用该方法

close_spider(spider)

当spider关闭的时候将调用该方法
Item Pipeline例子

代码如下:


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, item, 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, item, 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保存控制台信息到文本解析

Python爬虫实例爬取网站搞笑段子

Python爬虫获取整个站点中的所有外部链接代码示例

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

来源:http://blog.csdn.net/php_fly/article/details/19571121

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com