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安 ...
随机推荐
- arguments伪对象数组 javascript
arguments伪对象数组: <!DOCTYPE html> <html lang="en"> <head> <meta charset ...
- Flume+Kafka+Storm+Hbase+HDSF+Poi整合
Flume+Kafka+Storm+Hbase+HDSF+Poi整合 需求: 针对一个网站,我们需要根据用户的行为记录日志信息,分析对我们有用的数据. 举例:这个网站www.hongten.com(当 ...
- Linux进阶命令用法
1.tr命令 可以对来自标准输入的字符进行替换.压缩和删除.它可以将一组字符变成另一组字符 选项 -c或——complerment:取代所有不属于第一字符集的字符: -d或——delete:删除所有属 ...
- 编译部署 Mysql 5.7
1.环境准备 RHEL7.4(最小化安装) 64bit 2G 内存 (1G 内存编译将近一个小时) 磁盘空间 15G 以上. 配置为本地yum 源 从MySQL5.7版本开始,安装MySQL需要 ...
- 反编译python打包的exe文件
目录 1.前言 2.使用环境 3.还原过程 4.号外 5.exe文件和所用到的反编译工具 6.参考 7.去签名(补漏) 前言 拿到了利用驱动人生进行传播的病毒样本,发现是python打包成的exe文件 ...
- WebService常用接口链接(很全面,值得一看)
天气预报Web服务,数据来源于中国气象局Endpoint :http://www.webxml.com.cn/WebServices/WeatherWebService.asmxDisco ...
- pymongo的操作
实例化和插入 from pymongo import MongoClient class TestMongo: def __init__(self): client = MongoClient(hos ...
- echarts (geo/map) 渐变效果
这两天帮人搞了下中国范围内仓库量统计的需求,查了下echarts 里的文档找到类似的demo(链接:https://ecomfe.github.io/echarts-examples/public/e ...
- js-day01-js语言基础
JavaScript简介:JavaScript一种直译式脚本语言,是一种动态类型.弱类型.基于原型的语言,内置支持类型.它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本 ...
- js发送post请求,实现下载文件
由于业务需求要下载文件的功能: <!DOCTYPE html> <html> <head> <meta charset="utf-8"&g ...