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

yipeiwu_com6年前Python基础

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框架中Item Pipeline组件使用详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Python使用Scrapy保存控制台信息到文本解析

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

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

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

相关文章

Python安装第三方库及常见问题处理方法汇总

源码安装 Python第三方库几乎都可以在github或者 pypi上找到源码。源码包格式大概有zip 、 tar.zip、 tar.bz2。解压这些包,进入解压好的文件夹,通常会有一个...

Django基础知识 URL路由系统详解

Django基础知识 URL路由系统详解

MVC和MTV框架 MVC Web服务器开发领域里著名的MVC模式,所谓MVC就是把Web应用分为模型(M),控制器(C)和视图(V)三层,他们之间以一种插件式的、松耦合的方式连接在...

python一键去抖音视频水印工具

python一键去抖音视频水印工具

无水印视频下载 方法一: 无水印视频下载很简单,有一个通用的方法,就是使用去水印平台即可。 我使用的去水印平台是:http://douyin.iiilab.com/ 在输入框中输入视频链...

对tensorflow中的strides参数使用详解

在二维卷积函数tf.nn.conv2d(),最大池化函数tf.nn.max_pool(),平均池化函数 tf.nn.avg_pool()中,卷积核的移动步长都需要制定一个参数stride...

python3 http提交json参数并获取返回值的方法

如下所示: import json import http.client connection = http.client.HTTPSConnection('spd.aiopos...