scrapy框架之Pipeline管道类
Item Pipeline简介
Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清洗、验证和存储数据。
当页面被蜘蛛解析后,将被发送到Item管道,并经过几个特定的次序处理数据。
每个Item管道的组件都是有一个简单的方法组成的Python类。
他们获取了Item并执行他们的方法,同时他们还需要确定的是是否需要在Item管道中继续执行下一步或是直接丢弃掉不处理。
项目管道的执行过程
清理HTML数据
验证解析到的数据(检查Item是否包含必要的字段)
检查是否是重复数据(如果重复就删除)
将解析到的数据存储到数据库中
编写自己的Item Pipeline
每个项目管道组件是一个Python类,必须实现以下方法:
process_item(self, item, spider)
对于每个项目管道组件调用此方法。process_item() 必须返回一个带数据的dict,返回一个Item (或任何后代类)对象,返回一个Twisted Deferred或者raise DropItemexception。丢弃的项目不再由其他管道组件处理。
参数:
- item(Itemobject或dict) - 剪切的项目
- Spider(Spider对象) - 抓取物品的蜘蛛
另外,它们还可以实现以下方法:
# 当蜘蛛打开时调用此方法。
open_spider(self, spider) # 参数spider打开的蜘蛛 # 当蜘蛛关闭时调用此方法。
close_spider(self, spider) # 参数spider被关闭的蜘蛛 # 如果存在,则调用此类方法以从a创建流水线实例Crawler。它必须返回管道的新实例。Crawler对象提供对所有Scrapy核心组件(如设置和信号)的访问; 它是管道访问它们并将其功能挂钩到Scrapy中的一种方式。
from_crawler(cls, crawler) # 参数crawler(Crawlerobject) - 使用此管道的crawler
将抓取的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
删除重复项
假设在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,
}
图像管道
items
定义过滤字段
import scrapy class ImgpilelineproItem(scrapy.Item):
# define the fields for your item here like:
img_src = scrapy.Field()
spider
只是用来获取图片的下载地址并提交至itme
import scrapy
from imgPileLinePro.items import ImgpilelineproItem class ImgSpider(scrapy.Spider):
name = 'img'
# allowed_domains = ['www.xxx.com']
start_urls = ['http://pic.netbian.com/4kmeinv/']
url = 'http://pic.netbian.com/4kmeinv/index_%d.html'
page = 2 def parse(self, response):
li_list = response.xpath('//*[@id="main"]/div[3]/ul/li')
for li in li_list:
img_src = 'http://pic.netbian.com'+li.xpath('./a/img/@src').extract_first()
item = ImgpilelineproItem()
item['img_src'] = img_src yield item if self.page <= 2: # 爬取前两页
new_url = format(self.url%self.page)
self.page += 1
yield scrapy.Request(url=new_url,callback=self.parse)
pipelines
from scrapy.pipelines.images import ImagesPipeline
import scrapy # 用来下载图片的管道类
class ImgPileLine(ImagesPipeline):
#接收item且将item中存储的img_src进行请求发送
def get_media_requests(self,item,info):
yield scrapy.Request(url=item['img_src']) #指定数据存储的路径(文件夹【在配置文件中指定】+图片名称【该方法中返回】)
def file_path(self,request,response=None,info=None):
img_name = request.url.split('/')[-1]
return img_name #就是将item传递给下一个即将被执行的管道类
def item_completed(self,result,item,info):
return item
settings中的配置
# 指定文件的下载路径
IMAGES_STORE = './imgsLib' # 该文件会自动创建
# 启用管道
ITEM_PIPELINES = {
'imgPileLinePro.pipelines.ImgPileLine': 300,
}
将item写入到mongodb
import pymongo
class MongoPipeline(object):
def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
)
# 爬虫开始建立与mongodb的连接
def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]
# 爬虫结束断开与mongodb的连接
def close_spider(self, spider):
self.client.close()
# 数据存储
def process_item(self, item, spider):
# update 去重,以url_token为查找条件更新数据
self.db["user"].update({"url_token":item["url_token"]},{"$set":item},True)
return item
MONGO_URI = "localhost"
MONGO_DATABASE = "zhihu"
scrapy框架之Pipeline管道类的更多相关文章
- Scrapy框架-Item Pipeline
目录 1. Item Pipeline 3. 完善之前的案例: 3.1. item写入JSON文件 3.2. 启用一个Item Pipeline组件 3.3. 重新启动爬虫 1. Item Pipel ...
- scrapy框架系列 (5) Spider类
Spider Spider类定义了如何爬取某个(或某些)网站.包括了爬取的动作(例如:是否跟进链接)以及如何从网页的内容中提取结构化数据(爬取item). 换句话说,Spider就是您定义爬取的动作及 ...
- Scrapy框架——CrawlSpider类爬虫案例
Scrapy--CrawlSpider Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 此案例采用的是CrawlSpider类实现爬虫. 它是Spider的派生类,Spide ...
- Scrapy框架——CrawlSpider爬取某招聘信息网站
CrawlSpider Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页, 而Craw ...
- 爬虫Ⅱ:scrapy框架
爬虫Ⅱ:scrapy框架 step5: Scrapy框架初识 Scrapy框架的使用 pySpider 什么是框架: 就是一个具有很强通用性且集成了很多功能的项目模板(可以被应用在各种需求中) scr ...
- 都是干货---真正的了解scrapy框架
去重规则 在爬虫应用中,我们可以在request对象中设置参数dont_filter = True 来阻止去重.而scrapy框架中是默认去重的,那内部是如何去重的. from scrapy.dupe ...
- scrapy框架(三)
scrapy框架(三) CrawlSpider类 创建CrawlSpider # 创建项目后 $ scrapy genspider -t crawl spider_name website_doma ...
- Scrapy 框架 安装 五大核心组件 settings 配置 管道存储
scrapy 框架的使用 博客: https://www.cnblogs.com/bobo-zhang/p/10561617.html 安装: pip install wheel 下载 Twisted ...
- scrapy框架中Item Pipeline用法
scrapy框架中item pipeline用法 当Item 在Spider中被收集之后,就会被传递到Item Pipeline中进行处理 每个item pipeline组件是实现了简单的方法的pyt ...
随机推荐
- (三)ActiveMQ之发布- 订阅消息模式实现
一.概念 发布者/订阅者模型支持向一个特定的消息主题发布消息.0或多个订阅者可能对接收来自特定消息主题的消息感兴趣.在这种模型下,发布者和订阅者彼此不知道对方.这种模式好比是匿名公告板.这种模式被概括 ...
- (三)自定义Realm
一.Realm概念 Realm:域,Shiro从从Realm获取安全数据(如用户.角色.权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用 ...
- internal关键字
internal修饰符可以用于类型或成员,使用该修饰符声明的类型或成员只能在同一程集内访问,接口的成员不能使用internal修饰符. 就是使用internal的类只能在同一个项目中使用,不能在别的项 ...
- Spring IOC原理分析
IOC IOC(Inversion of Control)控制反转:所谓的控制反转,就是把原先需要我们代码自己实现对象的创建和依赖,反转给容器来实现.那么必然Spring需要创建一个容器,同时需要创建 ...
- Java中常见时间类的使用
模拟场景针对于常用的操作API,比如流操作(字符流.字节流),时间操作等,仅仅了解概念性的定义终究是无法了解该类的用途和使用方式:这种情况在使用的时候便一脸茫然,脑海中映射不到对应的知识点.本篇博客将 ...
- Atollic TrueSTUDIO编译选项-优化设置
最近在玩stm32f407,比较懒,就直接使用Atollic TrueSTUDIO,官方版本,还免费,但是编译后,一直感觉代码添加了优化,语句执行顺序和代码不一致,在线调试时,有些变量的数值被优化了, ...
- docker在Windows环境下的安装
Windows环境下安装 docker有两种安装包 一.Docker for Windows(目前只能在 64 位的 Windows10 专业版.企业版.教育版下才能安装) 二.Docker Tool ...
- C# Parellel.For 和 Parallel.ForEach
简介:任务并行库(Task Parellel Library)是BCL的一个类库,极大的简化了并行编程. 使用任务并行库执行循环C#当中我们一般使用for和foreach执行循环,有时候我们呢的循环结 ...
- How to resolve the 403 error when send POST request from Postman
Root cause: the site refused the connection from the http request origin, by default it is setted as ...
- Ubuntu系统---安装“搜狗拼音法”导致桌面打不开
Ubuntu系统---安装“搜狗拼音法”导致桌面打不开 ubuntu系统中文版,安装完后,自带中文输入法.中文用着好好的,用一段时间后,就会莫名的出现,切换不过来,中文输入不好用了.只是简单想装一个搜 ...