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. js合并table指定列

    function MergeTableCell(tableId, startRow, endRow, col) { var tb = document.getElementById(tableId); ...

  2. NOIP-螺旋矩阵

    题目描述 一个 n 行 n 列的螺旋矩阵可由如下方法生成: 从矩阵的左上角(第 1 行第 1 列)出发,初始时向右移动:如果前方是未曾经过的格子,则继续前进,否则右转:重复上述操作直至经过矩阵中所有格 ...

  3. Mac_Sublime Text3(mac)一些插件和快捷键

    下载地址http://www.sublimetext.com/3 一.安装Package Control 按Ctrl + ` 调出console,粘贴下列安装代码到底部命令行并回车: import u ...

  4. svn错误:更新源码出现校验和不匹配问题

    svn 的文本校验和不匹配: 最近在更新自动化源代码的时候出现了一个错误:svn: Checksum mismatch while updating.... 查了下google,原来是在更新源码出现校 ...

  5. React Native调试实用技巧,React Native开发者必会的调试技巧

    在做React Native开发时,少不了的需要对React Native程序进行调试.调试程序是每一位开发者的基本功,高效的调试不仅能提高开发效率,也能降低Bug率.本文将向大家分享React Na ...

  6. Java线程状态Jstack线程状态BLOCKED/TIMED_WAITING/WAITING解释

    一.线程5种状态 新建状态(New) 新创建了一个线程对象. 就绪状态(Runnable) 线程对象创建后,其他线程调用了该对象的start()方法.该状态的线程位于可运行线程池中,变得可运行,等待获 ...

  7. [Swift]LeetCode219. 存在重复元素 II | Contains Duplicate II

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j ...

  8. [Swift]LeetCode247.对称数 II $ Strobogrammatic Number II

    A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...

  9. [Swift]LeetCode255.验证二叉搜索树的先序序列 $ Verify Preorder Sequence in Binary Search Tree

    Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...

  10. [Swift]LeetCode632. 最小区间 | Smallest Range

    You have k lists of sorted integers in ascending order. Find the smallest range that includes at lea ...