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导出各种格式的更多相关文章

  1. SQL SERVER导出特殊格式的平面文件

    有时候我们需要将SQL SERVER的数据一次性导入到ORACLE中,对于数据量大的表.我一般习惯先从SQL SERVER导出特殊格式的平面文件(CSV或TXT),然后用SQL*Loader装载数据到 ...

  2. OAF_文件系列2_实现OAF导出CSV格式文件ExportButton(案例)

    20150727 Created By BaoXinjian

  3. Powerdesigner 导出Excel格式数据字典 导出Excel格式文件

    版权声明:本文为博主原创文章,转载请注明出处; 网上我也看到了很多的Powerdesigner 导出方法,因为Powerdesigner 提供了部分VBA功能,所以让我用代码导出Excel格式文件得以 ...

  4. 使用PHPExcel导入导出excel格式文件

    使用PHPExcel导入导出excel格式文件  作者:zccst  因为导出使用较多,以下是导出实现过程.  第一步,将PHPExcel的源码拷贝到项目的lib下  文件包含:PHPExcel.ph ...

  5. 导出CSV格式文件,用Excel打开乱码的解决办法

    导出CSV格式文件,用Excel打开乱码的解决办法 1.治标不治本的办法 将导出CSV数据文件用记事本打开,然后另存为"ANSI"编码格式,再用Excel打开,乱码解决. 但是,这 ...

  6. java导出csv格式文件

    导出csv格式文件的本质是导出以逗号为分隔的文本数据 import java.io.BufferedWriter; import java.io.File; import java.io.FileIn ...

  7. C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”

    报错信息: 最近打开下载的 Excel,会报如下错误.(xls 格式不受影响) 解决方案: 下载代码(红色为新添代码) public void download() { string fileName ...

  8. asp.net NPOI导出xlsx格式文件,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”

    NPOI导出xlsx格式文件,会出现如下情况: 点击“是”: 导出代码如下: /// <summary> /// 将datatable数据写入excel并下载 /// </summa ...

  9. 将页面中表格数据导出excel格式的文件(vue)

    近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...

随机推荐

  1. PHP常用日期加减计算方法实例

    PHP常用日期加减计算方法实例 实例总结了PHP常用日期加减计算方法.分享给大家供大家参考,具体如下: PHP 标准的日期格式 date("Y-m-d H:i:s"); PHP 简 ...

  2. 20181117-python第二章学习小结-part1

    什么是二进制,十进制如何转化成二进制. 在python上可使用简单的函数进行转化,bin() 数据量的基本关系: 1bit  就是0/1的一个单位 1bytes = 8bit    #1个字节,就是一 ...

  3. Linux 下redis 集群搭建练习

    Redis集群 学习参考:https://blog.csdn.net/jeffleo/article/details/54848428https://my.oschina.net/iyinghui/b ...

  4. python学习笔记(5)

    .................................................................................................... ...

  5. CSS grayscale滤镜+SVG使图片变黑白实例页面

    http:/CSS 地址:/www.runoob.com/cssref/css3-pr-filter.html CSS代码: .gray { -webkit-filter: grayscale(%); ...

  6. git教程——工作流程

    Git 工作流程 本章节我们将为大家介绍 Git 的工作流程. 一般工作流程如下: 克隆 Git 资源作为工作目录. 在克隆的资源上添加或修改文件. 如果其他人修改了,你可以更新资源. 在提交前查看修 ...

  7. vue 源码学习二 实例初始化和挂载过程

    vue 入口 从vue的构建过程可以知道,web环境下,入口文件在 src/platforms/web/entry-runtime-with-compiler.js(以Runtime + Compil ...

  8. Linux shell编程— 命令替换

    有两种方法可以将命令输出赋给变量 反引号字符(`) $()格式 命令替换允许你将shell 命令的输出赋给变量 要么用一对反引号把整个命令行围起来: testing=`data` 要么使用$()格式 ...

  9. centOS7上编译hadoop-2.7.7

    一.阅读编译文档 在hadoop源码包根目录下有个一个BUINDING.txt的文件,文件说明了编译hadoop所需要的一些编译hadoop所需要的一些编译环境相关的东西.不同hadoop版本的要求都 ...

  10. JavaScript 获取完整当前域名

    <script> var dq_url = window.location.protocol+"//"+window.location.host;/*获取当前域名*/ ...