itemexporters-scrapy框架8-python

文章目录

1 前言

我们爬取数据的目的,就是为了在其他应用或者系统中使用。为了方便使用,我们一般把爬取的数据持久化存储或者导出。关于持久化存储可以去参考之前pipeline章节以及python与数据库部分,这里主要讲解数据导出。

为此,Scrapy 提供了一组用于不同输出格式的项目导出器,例如 XML、CSV 或 JSON,以类XxxItemExporter的形式呈现。

2 item exporters

同样的在使用之前需要先实例化XxxItemExporter,那么我们先来看看都有哪些类。

2.1 Item Exporters

类名参数描述BaseItemExporter(fields_to_export=None, export_empty_fields=False, encoding=’utf-8′, indent=0, dont_fail=False)基础类PythonItemExporter(, dont_fail=False, kwargs)python格式XmlItemExporter(file, item_element=’item’, root_element=’items’, kwargs)xml格式CsvItemExporter(file, include_headers_line=True, join_multivalued=’,’, errors=None, kwargs)csv格式PickleItemExporter(file, protocol=0, kwargs)pickle格式PprintItemExporter(file, kwargs)打印格式JsonItemExporter(file, kwargs)json格式JsonLinesItemExporter(file, kwargs)json 行格式MarshalItemExporter(file, *args)marshal格式

  • 关于JsonItemExporter与JsonLinesItemExporter的分析
  • JsonItemExporter典型输出
[{"name": "Color TV", "price": "1200"},
{"name": "DVD player", "price": "200"}]
  • JsonLinesItemExporter典型输出
{"name": "Color TV", "price": "1200"}
{"name": "DVD player", "price": "200"}
  • JsonItemExporter输出规范,适用于小数据量的输出;JsonLinesItemExporter适用于大量的输出。

2.2 BaseItemExporter

BaseItemExporter为基础类,其他的都继承该类,下面我们以BaseItemExporter为例,介绍它的属性和方法。

  • 方法

方法名参数描述export_item()item导出itemserialize_field()file,name,value序列化字段start_exporting()开始导出,准备工作finish_exporting()介绍导出,收尾工作

  • 字段

字段名默认值描述export_empty_fieldsNone要导出的字段,默认导出全部字段encoding编码indent0缩进

2.3 实例化

2.3.1 必须条件

实例化需要实现一下3个方法:

  1. start_exporting()
  2. export_item()
  3. finish_exporting()

2.3.2 字段序列化

默认情况下,字段值由默认的序列化库执行序列化,当然我们也可以自定义实现,有以下2中方式:

  • 在字段中声明一个序列化器,示例:
import scrapy

def serialize_price(value):
    return f'$ {str(value)}'

class Product(scrapy.Item):
    name = scrapy.Field()
    price = scrapy.Field(serializer=serialize_price)
  • 重写serialize_field()方法,示例:
from scrapy.exporter import XmlItemExporter

class ProductXmlExporter(XmlItemExporter):

    def serialize_field(self, field, name, value):
        if name == 'price':
            return f'$ {str(value)}'
        return super().serialize_field(field, name, value)

2.4 项目实例

以我们之前的爬取csdn个人博客文章为例,现在我们要吧爬取的数据以json格式输出到文件中,pipelines.py代码实例:

class JSONPipeline:
    def __init__(self):
        self.fp = open("../../output/csdn.json", "wb")
        self.exporter = JsonItemExporter(self.fp, encoding='utf-8')

    def open_spider(self, spider):
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.fp.close()

输出:

[{"title": "process-进程详解-python", "publish": "2022-01-12 18:10:09", "approval": 0, "comment": 0, "collection": 0},...

2.5 自定义ItemExporter

现在很多应用特别是办公类,都需要和excel打交道,但是scrapy没有提供响应的导出器,你们我们参考BaseItemExporter自定义实现ExcelItemExporter。

详细过程参考链接:https://www.jianshu.com/p/a50b19b6258d

实例,以爬取csdn个人博客文章为例,pipeline代码

class ExcelPipeline:
    def __init__(self):
        self.fp = open("../../output/csdn.xls", "wb")
        self.exporter = ExcelItemExporter(self.fp, encoding='utf-8')

    def open_spider(self, spider):
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.fp.close()

itemexporters-scrapy框架8-python

3 后记

参考文章:

代码仓库:https://gitee.com/gaogzhen/python-study.git
QQ群:433529853

Original: https://blog.csdn.net/gaogzhen/article/details/125171386
Author: gaog2zh
Title: itemexporters-scrapy框架8-python

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/792328/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球