一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2018-01-16 编辑:猪哥 来源:一聚教程网

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之间

热门栏目