项目导出器
抓取到项目后,您通常希望持久化或导出这些项目,以便在其他应用程序中使用数据。毕竟,这是抓取过程的全部目的。
为此,Scrapy 提供了一系列项目导出器,支持不同的输出格式,例如 XML、CSV 或 JSON。
使用项目导出器
如果您时间紧迫,只想使用项目导出器输出抓取到的数据,请参阅Feed 导出。否则,如果您想了解项目导出器的工作原理或需要更多自定义功能(默认导出未涵盖),请继续阅读下文。
为了使用项目导出器,您必须使用其所需参数来实例化它。每个项目导出器需要不同的参数,因此请务必查阅每个导出器的文档,具体请参见内置项目导出器参考。实例化导出器后,您需要:
1. 调用方法start_exporting()以发出导出过程开始的信号
2. 对每个要导出的项目调用export_item()方法
3. 最后调用finish_exporting()以发出导出过程结束的信号
在这里,您可以看到一个项目管道,它使用多个项目导出器,根据其中一个字段的值将抓取到的项目分组到不同的文件中。
from itemadapter import ItemAdapter
from scrapy.exporters import XmlItemExporter
class PerYearXmlExportPipeline:
"""Distribute items across multiple XML files according to their 'year' field"""
def open_spider(self, spider):
self.year_to_exporter = {}
def close_spider(self, spider):
for exporter, xml_file in self.year_to_exporter.values():
exporter.finish_exporting()
xml_file.close()
def _exporter_for_item(self, item):
adapter = ItemAdapter(item)
year = adapter["year"]
if year not in self.year_to_exporter:
xml_file = open(f"{year}.xml", "wb")
exporter = XmlItemExporter(xml_file)
exporter.start_exporting()
self.year_to_exporter[year] = (exporter, xml_file)
return self.year_to_exporter[year][0]
def process_item(self, item):
exporter = self._exporter_for_item(item)
exporter.export_item(item)
return item
项目字段的序列化
默认情况下,字段值会未经修改地传递给底层序列化库,如何序列化它们的决定则委托给各个序列化库。
但是,您可以在字段值传递给序列化库之前自定义其序列化方式。
自定义字段序列化方式有两种,如下所述。
1. 在字段中声明序列化器
除了dict之外,所有项目类型都允许您在字段元数据中声明一个序列化器。该序列化器必须是一个可调用对象,它接收一个值并返回其序列化形式。
示例:
from dataclasses import dataclass, field
def serialize_price(value):
return f"$ {str(value)}"
@dataclass
class Product:
name: str
price: float = field(metadata={"serializer": serialize_price})
2. 覆盖 serialize_field() 方法
您还可以覆盖serialize_field()方法来自定义您的字段值将如何导出。
请确保在您的自定义代码之后调用基类的serialize_field()方法。
示例:
from scrapy.exporters 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)
内置项目导出器参考
以下是 Scrapy 附带的项目导出器列表。其中一些包含输出示例,这些示例假设您正在导出以下两个项目:
Item(name="Color TV", price="1200")
Item(name="DVD player", price="200")
BaseItemExporter
- class scrapy.exporters.BaseItemExporter(fields_to_export=None, export_empty_fields=False, encoding='utf-8', indent=0, dont_fail=False)[source]
这是所有项目导出器的(抽象)基类。它为所有(具体)项目导出器使用的通用功能提供支持,例如定义要导出的字段、是否导出空字段,或使用哪种编码。
这些功能可以通过
__init__方法参数进行配置,这些参数会填充各自的实例属性:fields_to_export、export_empty_fields、encoding、indent。- serialize_field(field, name, value)[source]
返回给定字段的序列化值。如果您想控制特定字段或值如何被序列化/导出,可以(在您的自定义项目导出器中)覆盖此方法。
默认情况下,此方法会查找项目字段中声明的序列化器,并返回将该序列化器应用于值的结果。如果未找到序列化器,则返回未更改的值。
- start_exporting()[source]
发出导出过程开始的信号。某些导出器可能会用此方法生成一些必需的头部(例如,
XmlItemExporter)。您必须在导出任何项目之前调用此方法。
- finish_exporting()[source]
发出导出过程结束的信号。某些导出器可能会用此方法生成一些必需的尾部(例如,
XmlItemExporter)。在没有更多项目要导出之后,您必须始终调用此方法。
- fields_to_export
要导出的字段、它们的顺序[1]及其输出名称。
可能的值有
None(所有字段[2],默认)字段列表
['field1', 'field2']
一个字典,其中键是字段,值是输出名称
{'field1': 'Field 1', 'field2': 'Field 2'}
- export_empty_fields
是否在导出的数据中包含空/未填充的项目字段。默认为
False。某些导出器(例如CsvItemExporter)会忽略此属性并始终导出所有空字段。对于 dict 项目,此选项被忽略。
- encoding
输出字符编码。
- indent
每级输出缩进使用的空格数量。默认为
0。indent=None选择最紧凑的表示形式,所有项目在同一行且无缩进。indent<=0每个项目单独一行,无缩进。indent>0每个项目单独一行,并按提供的数值缩进。
PythonItemExporter
XmlItemExporter
- class scrapy.exporters.XmlItemExporter(file, item_element='item', root_element='items', **kwargs)[source]
以 XML 格式将项目导出到指定的文件对象。
- 参数:
此
__init__方法的额外关键字参数将传递给BaseItemExporter的__init__方法。此导出器的典型输出将是
<?xml version="1.0" encoding="utf-8"?> <items> <item> <name>Color TV</name> <price>1200</price> </item> <item> <name>DVD player</name> <price>200</price> </item> </items>除非在
serialize_field()方法中被覆盖,否则多值字段通过在<value>元素内序列化每个值来导出。这是为了方便,因为多值字段非常常见。例如,项目
Item(name=['John', 'Doe'], age='23')
将序列化为
<?xml version="1.0" encoding="utf-8"?> <items> <item> <name> <value>John</value> <value>Doe</value> </name> <age>23</age> </item> </items>
CsvItemExporter
- class scrapy.exporters.CsvItemExporter(file, include_headers_line=True, join_multivalued=',', errors=None, **kwargs)[source]
以 CSV 格式将项目导出到给定的文件类对象。如果设置了
fields_to_export属性,它将用于定义 CSV 列、它们的顺序和列名。export_empty_fields属性对此导出器无效。- 参数:
file – 用于导出数据的文件类对象。其
write方法应接受bytes(例如以二进制模式打开的磁盘文件、io.BytesIO对象等)。include_headers_line (str) – 如果启用,导出器将输出一个标题行,其中包含从
BaseItemExporter.fields_to_export或第一个导出项目字段中获取的字段名称。join_multivalued – 用于连接多值字段(如果存在)的字符(或多个字符)。
errors (str) – 可选字符串,指定如何处理编码和解码错误。更多信息请参见
io.TextIOWrapper。
此
__init__方法的额外关键字参数将传递给BaseItemExporter的__init__方法,其余参数则传递给csv.writer()函数,因此您可以使用任何csv.writer()函数参数来自定义此导出器。此导出器的典型输出将是
product,price Color TV,1200 DVD player,200
PickleItemExporter
- class scrapy.exporters.PickleItemExporter(file, protocol=0, **kwargs)[source]
以 pickle 格式将项目导出到给定的文件类对象。
- 参数:
file – 用于导出数据的文件类对象。其
write方法应接受bytes(例如以二进制模式打开的磁盘文件、io.BytesIO对象等)。protocol (int) – 要使用的 pickle 协议。
更多信息请参见
pickle。此
__init__方法的额外关键字参数将传递给BaseItemExporter的__init__方法。Pickle 不是人类可读的格式,因此未提供输出示例。
PprintItemExporter
- class scrapy.exporters.PprintItemExporter(file, **kwargs)[source]
以美观打印格式将项目导出到指定的文件对象。
- 参数:
file – 用于导出数据的文件类对象。其
write方法应接受bytes(例如以二进制模式打开的磁盘文件、io.BytesIO对象等)。
此
__init__方法的额外关键字参数将传递给BaseItemExporter的__init__方法。此导出器的典型输出将是
{'name': 'Color TV', 'price': '1200'} {'name': 'DVD player', 'price': '200'}较长的行(如果存在)将进行美观格式化。
JsonItemExporter
- class scrapy.exporters.JsonItemExporter(file, **kwargs)[source]
以 JSON 格式将项目导出到指定的文件类对象,将所有对象作为对象列表写入。此
__init__方法的额外参数会传递给BaseItemExporter的__init__方法,而剩余的参数则传递给JSONEncoder的__init__方法,因此您可以使用任何JSONEncoder的__init__方法参数来自定义此导出器。- 参数:
file – 用于导出数据的文件类对象。其
write方法应接受bytes(例如以二进制模式打开的磁盘文件、io.BytesIO对象等)。
此导出器的典型输出将是
[{"name": "Color TV", "price": "1200"}, {"name": "DVD player", "price": "200"}]警告
JSON 是一种非常简单灵活的序列化格式,但对于大量数据来说,其可伸缩性不佳,因为 JSON 解析器(任何语言)对增量(即流模式)解析的支持不完善(甚至根本不支持),并且大多数解析器只在内存中解析整个对象。如果您想要 JSON 的强大和简洁性,同时需要更适合流处理的格式,请考虑使用
JsonLinesItemExporter,或者将输出分成多个块。
JsonLinesItemExporter
- class scrapy.exporters.JsonLinesItemExporter(file, **kwargs)[source]
以 JSON 格式将项目导出到指定的文件类对象,每行写入一个 JSON 编码的项目。此
__init__方法的额外参数会传递给BaseItemExporter的__init__方法,而剩余的参数则传递给JSONEncoder的__init__方法,因此您可以使用任何JSONEncoder的__init__方法参数来自定义此导出器。- 参数:
file – 用于导出数据的文件类对象。其
write方法应接受bytes(例如以二进制模式打开的磁盘文件、io.BytesIO对象等)。
此导出器的典型输出将是
{"name": "Color TV", "price": "1200"} {"name": "DVD player", "price": "200"}与
JsonItemExporter生成的格式不同,此导出器生成的格式非常适合序列化大量数据。