Item Pipeline(英文版):http://doc.scrapy.org/en/latest/topics/item-pipeline.html

Item Pipeline(中文版):https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/item-pipeline.html

Scrapy 1.3 文档  item Pipeline:https://oner-wv.gitbooks.io/scrapy_zh/content/基本概念/item管道.html

scrapy 多个pipeline:https://www.baidu.com/s?wd=scrapy 多个pipeline

不同的 spider item 如何指定不同的 pipeline处理?:https://segmentfault.com/q/1010000006890114?_ea=1166343

scrapy 源码 pipelines 目录下有三个文件:files.py、images.py、media.py 。scrapy 在这个三个文件中提供了三种不同的 pipeline 

  1. media.py:class MediaPipeline(object):可以下载 媒体

  2. files.py:class FilesPipeline(MediaPipeline):可以下载文件。FilesPipeline 继承 MediaPipeline
    Python3 scrapy下载网易云音乐所有(大部分)歌曲:https://blog.csdn.net/Heibaiii/article/details/79323634
  3. images.py:class ImagesPipeline(FilesPipeline)。可以下载图片,也可以自己写 pipeline 下载图片
    使用 ImagesPipeline 下载图片:https://blog.csdn.net/freeking101/article/details/87860892
    下载壁纸图,使用ImagesPipeline:https://blog.csdn.net/qq_28817739/article/details/79904391

Item Pipeline(项目管道)

在项目被蜘蛛抓取后,它被发送到项目管道,它通过顺序执行的几个组件来处理它。

每个项目管道组件(有时称为“Item Pipeline”)是一个实现简单方法的Python类。他们接收一个项目并对其执行操作,还决定该项目是否应该继续通过流水线或被丢弃并且不再被处理。

项目管道的典型用途是:

  • 清理HTML数据
  • 验证抓取的数据(检查项目是否包含特定字段)
  • 检查重复(并删除)
  • 将刮取的项目存储在数据库中

编写自己的项目管道

每个项目管道组件是一个Python类

process_item(self, item, spider)

每个项目管道组件都必须调用此方法。process_item() 必须:返回一个带数据的dict,返回一个Item (或任何后代类)对象,返回一个Twisted Deferred或者raise DropItemexception。丢弃的项目不再由其他管道组件处理。

参数:

  • item:( Itemobject 或 dict ) -
  • Spider:自己编写的 Spider ,即自定义的 Spider 类的对象

open_spider(self, spider):蜘蛛打开时调用 这个方法。

参数:spider:自己编写的 Spider ,即自定义的 Spider 类的对象

close_spider(self, spider):当蜘蛛关闭时调用此方法。

参数:spider:自己编写的 Spider ,即自定义的 Spider 类的对象

from_crawler(cls, crawler):

如果存在,则此类方法被调用,通过 Crawler 来创建一个 pipeline 实例。它必须返回管道的新实例。Crawler对象 提供对所有Scrapy核心组件(如设置和信号)的访问,它是管道访问它们并将其功能挂钩到Scrapy中的一种方式。

参数:crawler(Crawlerobject) - 使用此管道的 crawler

爬虫示例:

images.py:

# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from urllib.parse import urlencode
import jsonfrom images360.items import ImageItemclass ImagesSpider(Spider):name = 'images'allowed_domains = ['images.so.com']start_urls = ['http://images.so.com/']def start_requests(self):data = {'ch': 'photography', 'listtype': 'new'}base_url = 'https://image.so.com/zj?'for page in range(1, self.settings.get('MAX_PAGE') + 1):data['sn'] = page * 30params = urlencode(data)url = base_url + paramsyield Request(url, self.parse)def parse(self, response):result = json.loads(response.text)for image in result.get('list'):item = ImageItem()item['id'] = image.get('imageid')item['url'] = image.get('qhimg_url')item['title'] = image.get('group_title')item['thumb'] = image.get('qhimg_thumb_url')yield item

items.py:

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.htmlfrom scrapy import Item, Fieldclass ImageItem(Item):collection = table = 'images'id = Field()url = Field()title = Field()thumb = Field()

pipelines.py:

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport pymongo
import pymysql
from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipelineclass MongoPipeline(object):def __init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddef from_crawler(cls, crawler):return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DB'))def open_spider(self, spider):self.client = pymongo.MongoClient(self.mongo_uri)self.db = self.client[self.mongo_db]def process_item(self, item, spider):name = item.collectionself.db[name].insert(dict(item))return itemdef close_spider(self, spider):self.client.close()class MysqlPipeline():def __init__(self, host, database, user, password, port):self.host = hostself.database = databaseself.user = userself.password = passwordself.port = port@classmethoddef from_crawler(cls, crawler):return cls(host=crawler.settings.get('MYSQL_HOST'),database=crawler.settings.get('MYSQL_DATABASE'),user=crawler.settings.get('MYSQL_USER'),password=crawler.settings.get('MYSQL_PASSWORD'),port=crawler.settings.get('MYSQL_PORT'),)def open_spider(self, spider):self.db = pymysql.connect(self.host, self.user, self.password, self.database, charset='utf8',port=self.port)self.cursor = self.db.cursor()def close_spider(self, spider):self.db.close()def process_item(self, item, spider):print(item['title'])data = dict(item)keys = ', '.join(data.keys())values = ', '.join(['%s'] * len(data))sql = 'insert into %s (%s) values (%s)' % (item.table, keys, values)self.cursor.execute(sql, tuple(data.values()))self.db.commit()return itemclass ImagePipeline(ImagesPipeline):def file_path(self, request, response=None, info=None):url = request.urlfile_name = url.split('/')[-1]return file_namedef item_completed(self, results, item, info):image_paths = [x['path'] for ok, x in results if ok]if not image_paths:raise DropItem('Image Downloaded Failed')return itemdef get_media_requests(self, item, info):yield Request(item['url'])

项目管道示例

价格验证和丢弃项目没有价格

让我们来看看以下假设的管道,它调整 price那些不包括增值税(price_excludes_vat属性)的项目的属性,并删除那些不包含价格的项目:

from scrapy.exceptions import DropItemclass PricePipeline(object):vat_factor = 1.15def process_item(self, item, spider):if item['price']:if item['price_excludes_vat']:item['price'] = item['price'] * self.vat_factorreturn itemelse:raise DropItem("Missing price in %s" % item)

将项目写入JSON文件

以下管道将所有抓取的项目(来自所有蜘蛛)存储到单个items.jl文件中,每行包含一个项目,以JSON格式序列化:

import jsonclass JsonWriterPipeline(object):def open_spider(self, spider):self.file = open('items.jl', 'wb')def close_spider(self, spider):self.file.close()def process_item(self, item, spider):line = json.dumps(dict(item)) + "\n"self.file.write(line)return item

注意

JsonWriterPipeline的目的只是介绍如何编写项目管道。如果您真的想要将所有抓取的项目存储到JSON文件中,则应使用Feed导出。

将项目写入MongoDB

在这个例子中,我们使用pymongo将项目写入MongoDB。MongoDB地址和数据库名称在Scrapy设置中指定; MongoDB集合以item类命名。

这个例子的要点是显示如何使用from_crawler()方法和如何正确清理资源:

import pymongoclass MongoPipeline(object):collection_name = 'scrapy_items'def __init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddef 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

拍摄项目的屏幕截图

此示例演示如何从方法返回Deferredprocess_item()。它使用Splash来呈现项目网址的屏幕截图。Pipeline请求本地运行的Splash实例。在请求被下载并且Deferred回调触发后,它将项目保存到一个文件并将文件名添加到项目。

import scrapy
import hashlib
from urllib.parse import quoteclass ScreenshotPipeline(object):"""Pipeline that uses Splash to render screenshot ofevery Scrapy item."""SPLASH_URL = "http://localhost:8050/render.png?url={}"def process_item(self, item, spider):encoded_item_url = quote(item["url"])screenshot_url = self.SPLASH_URL.format(encoded_item_url)request = scrapy.Request(screenshot_url)dfd = spider.crawler.engine.download(request, spider)dfd.addBoth(self.return_item, item)return dfddef return_item(self, response, item):if response.status != 200:# Error happened, return item.return item# Save screenshot to file, filename will be hash of url.url = item["url"]url_hash = hashlib.md5(url.encode("utf8")).hexdigest()filename = "{}.png".format(url_hash)with open(filename, "wb") as f:f.write(response.body)# Store filename in item.item["screenshot_filename"] = filenamereturn item

重复过滤器

用于查找重复项目并删除已处理的项目的过滤器。假设我们的项目具有唯一的ID,但是我们的蜘蛛会返回具有相同id的多个项目:

from scrapy.exceptions import DropItemclass 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

激活项目管道组件

要激活项目管道组件,必须将其类添加到 ITEM_PIPELINES设置,类似于以下示例:

ITEM_PIPELINES = {'myproject.pipelines.PricePipeline': 300,'myproject.pipelines.JsonWriterPipeline': 800,
}

您在此设置中分配给类的整数值确定它们运行的​​顺序:项目从较低值到较高值类。通常将这些数字定义在0-1000范围内。

Scrapy-Item Pipeline(项目管道)相关推荐

  1. 如何用item pipeline(管道)清洗数据

    管道是什么 Item管道(Item Pipeline): 主要负责处理有蜘蛛从网页中抽取的Item,主要任务是清洗.验证和存储数据. 当页面被蜘蛛解析后,将被发送到Item管道,并经过几个特定的次序处 ...

  2. scrapy链接mysql_Scrapy存入MySQL(四):scrapy item pipeline组件实现细节

    Scrapy存入MySQL或是其他数据库,虽然scrapy没有给我们提供拿来就用的类,但是她已经给我们实现了部分方法,我们继承它给我们实现的方法就能轻松的把数据存入你想存入的数据库,那我们要肿么继承呢 ...

  3. 第45讲:哪都能存,Item Pipeline 的用法

    在前面的示例中我们已经了解了 Item Pipeline 项目管道的基本概念,本节课我们就深入详细讲解它的用法. 首先我们看看 Item Pipeline 在 Scrapy 中的架构,如图所示. 图中 ...

  4. scrapy使用item,pipeline爬取数据,并且上传图片到oss

    Scrapy原理图 首先是要理解scrapy的运作原理是什么.这里不做解释,网上有很多资源可以理解. 声明item对象 明确了需要爬取哪些字段,就现在items.py里面定义字段 import scr ...

  5. python pipeline框架_爬虫(十六):Scrapy框架(三) Spider Middleware、Item Pipeline|python基础教程|python入门|python教程...

    https://www.xin3721.com/eschool/pythonxin3721/ 1. Spider Middleware Spider Middleware是介入到Scrapy的Spid ...

  6. 玩转 Scrapy 框架 (一):Item Pipeline 的使用

    目录 一.核心方法 二.实战:获取图片(仅学习使用) 2.1 简单分析 2.2 编码 三.总结 Item Pipeline 即项目管道,调用发生在 Spider 产生 Item 之后,当 Spider ...

  7. python pipeline框架_Python爬虫从入门到放弃(十六)之 Scrapy框架中Item Pipeline用法...

    原博文 2017-07-17 16:39 − 当Item 在Spider中被收集之后,就会被传递到Item Pipeline中进行处理 每个item pipeline组件是实现了简单的方法的pytho ...

  8. scrapy爬虫之item pipeline保存数据

    ##简介 前面的博文我们都是使用"-o ***.josn"参数将提取的item数据输出到json文件,若不加此参数提取到的数据则不会输出.其实当Item在Spider中被收集之后, ...

  9. scrapy使用pipeline保存不同的表单Item到数据库、本地文件

    文章目录 步骤1:构造Item 步骤2:构造Pipeline 步骤3:setting配置pipeline 步骤1:构造Item import scrapyclass StockItem(scrapy. ...

最新文章

  1. iOS开发 - 百度地图后台持续定位
  2. 【Matlab 控制】构建系统,绘制零极点
  3. BML CodeLab重磅更新:在Windows上可原生Linux AI开发
  4. C/C++学习之路_六: 指针
  5. .NET Forms身份验证
  6. 一定备足货!卢伟冰再曝红米骁龙855旗舰:性价比之王
  7. python爬取微博恶评_Python爬取新浪微博评论数据,了解一下?
  8. 软件设计师备考知识03
  9. 前端工程化(Vue-cli3和Element-ui)
  10. 【尚未完成,不建议参考】马氏距离,汉明距离
  11. 如何有效地刷算法题?
  12. 配置跳转指定_SpaceVim 中自定义工程文件跳转
  13. 让你做个《五子棋》怎么存储棋盘上的棋子信息?
  14. java extjs combobox_Extjs 教程三 “combobox”
  15. 使用HttpClient下载网络图片
  16. x264码率控制介绍、配置及应用
  17. 职称计算机考试相当于几级,全国职称计算机考试与全国计算机等级考试有什么不同?...
  18. 什么电子邮箱最安全,什么邮箱更具私密性?
  19. Python实验-小黑屋
  20. Bunch转化为DataFrame的一般方法

热门文章

  1. Spring Boot开发Web应用
  2. 美团开源 Logan Web:前端日志在 Web 端的实现
  3. 论文浅尝 | 基于时序知识图谱的问答
  4. 论文浅尝 | 实体图的预览表格生成
  5. CCKS 2018 | 前沿技术讲习班
  6. python实现大批量pdf格式论文的重命名与目录制作功能
  7. svn中文语言包安装(最详细步骤)+Language Pack+TortoiseSVN 安装
  8. 2021-11-06深度学习
  9. SIRIM上海,http://www.sirim-global.com
  10. Leetcode905.Sort Array By Parity按奇偶排序数组