Scrapy-Item Pipeline(项目管道)

 

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范围内。

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/495924.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java8 Stream详解~筛选:filter

筛选&#xff0c;是按照一定的规则校验流中的元素&#xff0c;将符合条件的元素提取到新的流中的操作。 「案例一&#xff1a;筛选出Integer集合中大于7的元素&#xff0c;并打印出来」 public class StreamTest {public static void main(String[] args) {List<Integer>…

Scrapy-Item Loaders(项目加载器)

Item Loaders&#xff1a;http://doc.scrapy.org/en/latest/topics/loaders.html Item Loaders&#xff08;中文版&#xff09;&#xff1a;https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/loaders.html 项目加载器 Item Loaders&#xff08;项目加载器&#xff09; …

《全球人工智能产业地图》发布(附PPT图片)

来源&#xff1a;中国信息通信研究院CAICT摘要&#xff1a;工业和信息化部、电子信息企业、人工智能企业、互联网企业、电信运营商、研究机构、社团组织、高校等代表参会&#xff0c;一致对《全球人工智能产业地图》表示高度肯定和认可。2018年4月10日&#xff0c;在工业和信息…

程序员如何追女孩

我是女生&#xff0c;看到有的男生想追自己喜欢的女孩子又不敢追&#xff0c;还想人家倒追她&#xff0c;我很反感. 从一个女生的角度&#xff0c;我比较了解女孩子的心理。女孩子大多不会主动出击&#xff0c;去追求自己喜欢的男孩&#xff0c;除了确实太喜欢了或者是那种比较…

Scrapy-spiders(爬虫)

Scrapy Spiders&#xff08;中文版&#xff09;&#xff1a;http://doc.scrapy.org/en/latest/topics/spiders.html Scrapy Spiders&#xff08;中文版&#xff09;&#xff1a;https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/spiders.html Scrapy 1.3 文档&#xf…

Java8 Stream详解~聚合(max/min/count)

max、min、count这些字眼你一定不陌生&#xff0c;没错&#xff0c;在mysql中我们常用它们进行数据统计。Java stream中也引入了这些概念和用法&#xff0c;极大地方便了我们对集合、数组的数据统计工作。 「案例一&#xff1a;获取String集合中最长的元素。」 public class S…

为何学习新知识这么难?因为大脑可能比你想象中更死板

来源&#xff1a;科研圈撰文 John Rennie 翻译 齐睿娟 审校 魏潇某些情况下&#xff0c;大脑的适应能力似乎是用之不竭的。但通过观察学习状态下的大脑活动&#xff0c;科学家们发现&#xff0c;这一过程中大脑的神经元网络功能出乎意料地死板和低效。学习能力是人类智力的…

vs2010 学习Silverlight学习笔记(8):使用用户控件

概要&#xff1a; 这个类似于封装控件样式。不过封装的是整个或是多个控件罢了&#xff0c;然后用的时候就可以直接引用过来了。 创建用户控&#xff1a; 这个也很简单&#xff0c;不过有几个地方需要注意下。这个就不照抄了&#xff0c;咱们也自己写一个。  步骤&#xff1a…

群雄逐鹿,谁将赢得5G时代的物联网战争?

来源&#xff1a;IT港摘要&#xff1a;5G时代的物联网机遇&#xff0c;是一次重大产业变革机会&#xff0c;谁都不想错过&#xff0c;但谁能享受到这波红利&#xff0c;我们还需拭目以待。日本首富&#xff0c;软银集团创始人孙正义是全球科技界的传奇&#xff0c;他曾投资了两…

Java8 Stream详解~映射(map/flatMap)

映射&#xff0c;可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap&#xff1a; map&#xff1a;接收一个函数作为参数&#xff0c;该函数会被应用到每个元素上&#xff0c;并将其映射成一个新的元素。 flatMap&#xff1a;接收一个函数作为参数&…

Scrapy-redis 源码分析 及 框架使用

From&#xff1a;https://blog.csdn.net/weixin_37947156/article/details/75044971 From&#xff1a;https://cuiqingcai.com/6058.html Scrapy-redis github&#xff1a;https://github.com/rmax/scrapy-redis scrapy-redis分布式爬虫框架详解&#xff1a;https://segmentfa…

收集一些.NET开发资源站点和部分优秀.NET开源项目 (转)

收集一些.NET开发资源站点和部分优 秀.NET开源项目 微软.Net中文主页 .NET Framework开发中心 微软.Net Framework中文产品支持中心 微软.Net Framework中文新闻组(Web) 微软VB.Net中文新闻组(Web) 博客园 .NET 2.0 专题 孟宪会之精彩世界 微软.NET俱乐部 MSDN中文网络广播 As…

Java8 Stream详解~归约(reduce)

归约&#xff0c;也称缩减&#xff0c;顾名思义&#xff0c;是把一个流缩减成一个值&#xff0c;能实现对集合求和、求乘积和求最值操作。 「案例一&#xff1a;求Integer集合的元素之和、乘积和最大值。」 public class StreamTest {public static void main(String[] args) …

人工智能除了创造新材料还能预测化学反应性能

来源&#xff1a; 材料牛摘要&#xff1a; 在材料化学领域人工智能也在发挥着越来越重要的作用&#xff0c;往往研究人员想尽脑汁做不出来的东西它可以经过成千上万次的计算给出最优答案。【引言】机器学习方法正在成为众多学科科学探究的一部分。 机器学习&#xff08;ML&…

scrapy-redis 配置 settings

From&#xff1a;https://blog.csdn.net/weixin_37947156/article/details/75082061 小白进阶之Scrapy第三篇&#xff08;基于Scrapy-Redis的分布式以及cookies池&#xff09;&#xff1a;https://cuiqingcai.com/4048.html 开始之前我们得知道scrapy-redis的一些配置&#xf…

叶问2

编剧都死绝了&#xff1f;这么弱智的剧情&#xff01;还不如直接请甄子丹拍武打教学片&#xff01;还有那个狗屁《十月围城》居然是金像奖的大赢家&#xff0c;真他妈的活见鬼&#xff01;转载于:https://www.cnblogs.com/uwenida/archive/2010/05/11/1732983.html

推荐|深度学习领域引用量最多的前20篇论文简介

来源&#xff1a;全球人工智能作者&#xff1a;Pedro Lopez&#xff0c;数据科学家&#xff0c;从事金融与商业智能。译者&#xff1a;海棠&#xff0c;审阅&#xff1a;袁虎。深度学习是机器学习和统计学交叉领域的一个子集&#xff0c;在过去的几年里得到快速的发展。强大的开…

Java8 Stream详解~收集(collect)

collect&#xff0c;收集&#xff0c;可以说是内容最繁多、功能最丰富的部分了。从字面上去理解&#xff0c;就是把一个流收集起来&#xff0c;最终可以是收集成一个值也可以收集成一个新的集合。 1 归集(toList/toSet/toMap) 因为流不存储数据&#xff0c;那么在流中的数据完…

CrawlSpider 详解

From&#xff1a;https://blog.csdn.net/weixin_37947156/article/details/75604163 CrawlSpider是爬取那些具有一定规则网站的常用的爬虫&#xff0c;它基于Spider并有一些独特属性 rules: 是Rule对象的集合&#xff0c;用于匹配目标网站并排除干扰parse_start_url: 用于爬取…

MFC中实现的画箭头算法 (Arrow in MFC)

在codeproject中寻找到一个这样的算法,在这里介绍一下 可以改变三角形大小,顶点角度,是否填充和填充颜色等 但是画出的箭头还是不够美观....呵呵,还好吧 其中填充是代表箭头内是否填充颜色 先来看声明和实现 //使用一个结构体来存储相关的信息//Defines the attributes of…