scrapy pipelines导出各种格式
scrapy在使用pipelines的时候,我们经常导出csv,json.jsonlines等等格式。每次都需要写一个类去导出,很麻烦。
这里我整理一个pipeline文件,支持多种格式的。
# -*- 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.html # -*- 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.html from scrapy import signals
from scrapy.exporters import *
import logging
logger=logging.getLogger(__name__)
class BaseExportPipeLine(object):
def __init__(self,**kwargs):
self.files = {}
self.exporter=kwargs.pop("exporter",None)
self.dst=kwargs.pop("dst",None)
self.option=kwargs
@classmethod
def from_crawler(cls, crawler):
pipeline = cls()
crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
return pipeline def spider_opened(self, spider):
file = open(self.dst, 'wb')
self.files[spider] = file
self.exporter = self.exporter(file,**self.option)
self.exporter.start_exporting() def spider_closed(self, spider):
self.exporter.finish_exporting()
file = self.files.pop(spider)
file.close() def process_item(self, item, spider):
self.exporter.export_item(item)
return item #
# 'fields_to_export':["url","edit_url","title"] 设定只导出部分字段,以下几个pipeline都支持这个参数
# 'export_empty_fields':False 设定是否导出空字段 以下几个pipeline都支持这个参数
# 'encoding':'utf-8' 设定默认编码,以下几个pipeline都支持这个参数
# 'indent' :1: 设置缩进,这个参数主要给JsonLinesExportPipeline使用
# "item_element":"item"设置xml节点元素的名字,只能XmlExportPipeline使用,效果是<item></item>
# "root_element":"items"设置xml根元素的名字,只能XmlExportPipeline使用,效果是<items>里面是很多item</items>
# "include_headers_line":True 是否包含字段行, 只能CsvExportPipeline使用
# "join_multivalued":","设置csv文件的分隔符号, 只能CsvExportPipeline使用
# 'protocol':2设置PickleExportPipeline 导出协议,只能PickleExportPipeline使用
# "dst":"items.json" 设置目标位置
class JsonExportPipeline(BaseExportPipeLine):
def __init__(self):
option={"exporter":JsonItemExporter,"dst":"items.json","encoding":"utf-8","indent":4,}
super(JsonExportPipeline, self).__init__(**option)
class JsonLinesExportPipeline(BaseExportPipeLine):
def __init__(self):
option={"exporter":JsonLinesItemExporter,"dst":"items.jl","encoding":"utf-8"}
super(JsonLinesExportPipeline, self).__init__(**option)
class XmlExportPipeline(BaseExportPipeLine):
def __init__(self):
option={"exporter":XmlItemExporter,"dst":"items.xml","item_element":"item","root_element":"items","encoding":'utf-8'}
super(XmlExportPipeline, self).__init__(**option)
class CsvExportPipeline(BaseExportPipeLine):
def __init__(self):
# 设置分隔符的这个,我这里测试是不成功的
option={"exporter":CsvItemExporter,"dst":"items.csv","encoding":"utf-8","include_headers_line":True, "join_multivalued":","}
super(CsvExportPipeline, self).__init__(**option)
class PickleExportPipeline(BaseExportPipeLine):
def __init__(self):
option={"exporter":PickleItemExporter,"dst":"items.pickle",'protocol':2}
super(PickleExportPipeline, self).__init__(**option)
class MarshalExportPipeline(BaseExportPipeLine):
def __init__(self):
option={"exporter":MarshalItemExporter,"dst":"items.marsha"}
super(MarshalExportPipeline, self).__init__(**option)
class PprintExportPipeline(BaseExportPipeLine):
def __init__(self):
option={"exporter":PprintItemExporter,"dst":"items.pprint.jl"}
super(PprintExportPipeline, self).__init__(**option)
上面的定义好之后。我们就可以在settings.py里面设置导出指定的类了。
ITEM_PIPELINES = {
'ScrapyCnblogs.pipelines.PprintExportPipeline': 300,
#'ScrapyCnblogs.pipelines.JsonLinesExportPipeline': 302,
#'ScrapyCnblogs.pipelines.JsonExportPipeline': 303,
#'ScrapyCnblogs.pipelines.XmlExportPipeline': 304,
}
是不是很强大。如果你感兴趣,可以去github上找找这个部分的源码,地址如下:https://github.com/scrapy/scrapy/blob/master/scrapy/exporters.py
exporters的测试代码在这个位置:https://github.com/scrapy/scrapy/blob/master/tests/test_exporters.py,有兴趣的话,可以拜读下人家的源码吧。
详细的使用案例,可以参考我的一个github项目:https://github.com/zhaojiedi1992/ScrapyCnblogs
scrapy pipelines导出各种格式的更多相关文章
- SQL SERVER导出特殊格式的平面文件
有时候我们需要将SQL SERVER的数据一次性导入到ORACLE中,对于数据量大的表.我一般习惯先从SQL SERVER导出特殊格式的平面文件(CSV或TXT),然后用SQL*Loader装载数据到 ...
- OAF_文件系列2_实现OAF导出CSV格式文件ExportButton(案例)
20150727 Created By BaoXinjian
- Powerdesigner 导出Excel格式数据字典 导出Excel格式文件
版权声明:本文为博主原创文章,转载请注明出处; 网上我也看到了很多的Powerdesigner 导出方法,因为Powerdesigner 提供了部分VBA功能,所以让我用代码导出Excel格式文件得以 ...
- 使用PHPExcel导入导出excel格式文件
使用PHPExcel导入导出excel格式文件 作者:zccst 因为导出使用较多,以下是导出实现过程. 第一步,将PHPExcel的源码拷贝到项目的lib下 文件包含:PHPExcel.ph ...
- 导出CSV格式文件,用Excel打开乱码的解决办法
导出CSV格式文件,用Excel打开乱码的解决办法 1.治标不治本的办法 将导出CSV数据文件用记事本打开,然后另存为"ANSI"编码格式,再用Excel打开,乱码解决. 但是,这 ...
- java导出csv格式文件
导出csv格式文件的本质是导出以逗号为分隔的文本数据 import java.io.BufferedWriter; import java.io.File; import java.io.FileIn ...
- C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
报错信息: 最近打开下载的 Excel,会报如下错误.(xls 格式不受影响) 解决方案: 下载代码(红色为新添代码) public void download() { string fileName ...
- asp.net NPOI导出xlsx格式文件,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
NPOI导出xlsx格式文件,会出现如下情况: 点击“是”: 导出代码如下: /// <summary> /// 将datatable数据写入excel并下载 /// </summa ...
- 将页面中表格数据导出excel格式的文件(vue)
近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...
随机推荐
- 8.3-8.4NOIP模拟题总结
一:成绩 Day1 score=100+100+20 Day2 score=100+30+0 这成绩还是不行啊,仍需继续加油(抱怨一句暴力分有点少#滑稽) 二:题目分析 Day1 T1祖孙询问: 已知 ...
- PeopleSoft OLE Automation error in Workbooks.Open: ObjectDoMethod: Microsoft Excel 不能访问文件
os: WinServer 2012 R2 64位 问题描述:PeopleSoft Web端运行AE 报上图错误,AD工具直接Test正常 解决方案: 运行> dcomcnfg 这将打开组件服务 ...
- 删除PeopleSoft Process Scheduler服务器定义
DELETE FROM PS_SERVERDEFN WHERE SERVERNAME= 'PSNT2' ; DELETE FROM PSSERVERSTAT where SERVERNAME = 'P ...
- Linux系统如何添加IP别名
IP别名可以在一块物理网卡上绑定多个IP地址,这样就能够在使用单一网卡的同一个服务器上运行多个基于IP的虚拟主机,简单来说,IP别名就是一张物理网卡上配置多个IP,实现类似子接口之类的功能. 那么IP ...
- win10 anaconda安装后使用报错“Original error was: DLL load failed: 找不到指定的模块”
报错:Original error was: DLL load failed: 找不到指定的模块. 环境变量需要添加3个 然后就okay了.
- socket 套接字服务器端和客户端发送信息
import socket import threading host='' port=6889 def cilenThred(conn,addr): print("成功接受客户端{}的连接 ...
- [转]jenkins2 插件安装
文章来自:http://www.ciandcd.com 文中的代码来自可以从github下载: https://github.com/ciandcd Jenkins的安装包和插件在7个国家有20多个镜 ...
- MYSQL数据库数据拆分之分库分表总结
数据存储演进思路一:单库单表 单库单表是最常见的数据库设计,例如,有一张用户(user)表放在数据库db中,所有的用户都可以在db库中的user表中查到. 数据存储演进思路二:单库多表 随着用户数量的 ...
- [Swift]LeetCode62. 不同路径 | Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...
- [Java]LeetCode138. 复制带随机指针的链表 | Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point t ...