scrapy中的Pipeline
2024-10-21 03:48:44
当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item。
每个Item Pipeline都是实现了简单方法的Python类,比如决定此Item是丢弃而存储。以下是item pipeline的一些典型应用:
- 验证爬取的数据(检查item包含某些字段,比如说name字段)
- 查重(并丢弃)
- 将爬取结果保存到文件或者数据库中
编写item pipeline
编写item pipeline很简单,item pipiline组件是一个独立的Python类,其中process_item()方法必须实现:
import something class SomethingPipeline(object):
def __init__(self):
# 可选实现,做参数初始化等
# doing something def process_item(self, item, spider):
# item (Item 对象) – 被爬取的item
# spider (Spider 对象) – 爬取该item的spider
# 这个方法必须实现,每个item pipeline组件都需要调用该方法,
# 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。
return item def open_spider(self, spider):
# spider (Spider 对象) – 被开启的spider
# 可选实现,当spider被开启时,这个方法被调用。 def close_spider(self, spider):
# spider (Spider 对象) – 被关闭的spider
# 可选实现,当spider被关闭时,这个方法被调用
tem写入JSON文件
以下pipeline将所有(从所有'spider'中)爬取到的item,存储到一个独立地items.json 文件,每行包含一个序列化为'JSON'格式的'item':
# -*- coding: utf-8 -*- # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json class LoadermanPipeline(object): def __init__(self):
self.file = open('loaderman.json', 'w')
# self.file.write("[") def process_item(self, item, spider): jsontext = json.dumps(dict(item), ensure_ascii=False) + " ,\n" self.file.write(jsontext.encode("utf-8")) return item def close_spider(self, spider):
# self.file.write("]")
self.file.close()
为了启用Item Pipeline组件,必须将它的类添加到 settings.py文件ITEM_PIPELINES 配置,如下:
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'scrapyDemo.pipelines.ScrapydemoPipeline': 300,
#} ITEM_PIPELINES = { 'scrapyDemo.pipelines.LoadermanPipeline': 300,
}
分配给每个类的整型值,确定了他们运行的顺序,item按数字从低到高的顺序,通过pipeline,通常将这些数字定义在0-1000范围内(0-1000随意设置,数值越低,组件的优先级越高)
重新启动爬虫
将LoadermanSpider中的parse()方法修改代码如下,
# -*- coding: utf-8 -*-
import scrapy from scrapyDemo.items import LoadermanItem class LoadermanSpider(scrapy.Spider):
name = 'loaderman'
allowed_domains = ['http://www.cnblogs.com']
start_urls = ['http://www.cnblogs.com/loaderman'] def parse(self, response):
# filename = "loaderman.html"
# open(filename, 'w').write(response.body)
xpathList = response.xpath("//div[@class='post']")
# items= []
for each in xpathList:
# 将我们得到的数据封装到一个 `LoadermanItem` 对象 item = LoadermanItem() # extract()方法返回的都是unicode字符串
title = each.xpath(".//h2/a[@class='postTitle2']/text()").extract()
detailUrl = each.xpath(".//a[@class='postTitle2']/@href").extract()
content = each.xpath(".//div[@class='c_b_p_desc']/text()").extract()
date = each.xpath(".//p[@class='postfoot']/text()").extract()
# xpath返回的是包含一个元素的列表 item['title'] = title[0]
item['detailUrl'] = detailUrl[0]
item['content'] = content[0]
item['date'] = date[0]
# items.append(item)
# #将获取的数据交给pipelines
yield items # 返回数据,不经过pipeline
# return items
然后执行下面的命令:
scrapy crawl loaderman
查看当前目录是否生成loaderman
.json
最新文章
- 2.1 -1.0 Xcode(发布时间、使用、快捷键、插件相关)
- surface实例-小球弹起事例
- MyBatis自定义数据映射TypeHandler
- Weka算法Classifier-tree-J48源代码分析(一个)基本数据结构和算法
- DotNetBar v12.7.0.10 Fully Cracked
- Pots of gold game:看谁拿的钱多
- 学习笔记-[Maven实战]-第三章:Maven使用入门(2)
- Excel 2007中的新文件格式
- 多目标遗传算法 ------ NSGA-II (部分源码解析) 交叉操作 crossover.c
- 理解MVC路由配置(转)
- wordpress一些常用代码
- Nginx+Tomcat7+Mencached负载均衡集群部署笔记
- CSS3 制作向左、向右及关闭图标的效果 (另一种思路)
- WCF连接被意外关闭
- HDU 1160 FatMouse's Speed 动态规划 记录路径的最长上升子序列变形
- Word Ladder II 2015年6月4日
- Docker-通过docker-maven-plugin插件实现docker镜像构建并自动发布到远程docker服务器
- python操作符笔记
- 香茅油:不只是驱虫剂 new
- phpstorm连接服务器,实时编辑上传文件到服务器
热门文章
- Could not get lock /var/lib/dpkg/lock-frontend解决
- mysql查看表的属性 mysql将查询结果给临时变量
- 项目Beta冲刺(团队)——总结篇
- 项目Beta冲刺(团队5/7)
- Intellij IDEA运行报Command line is too long解法
- NameNode和SecondaryNameNode
- 品优购 Angular学习
- Mac安装vue.js开发环境
- es6字符串扩展 -- 字符串长度补全功能 padStart(), padEnd()
- 基本例程(4-1)手势识别C++ 和简单形状匹配