项目出口商¶
一旦你抓取了你的项目,你经常想要持久或导出这些项目,以使用其他应用程序中的数据。也就是说,毕竟刮削过程的整个目的。
为此目的,Scrapy为不同的输出格式(如XML,CSV或JSON)提供了一个项目导出器的集合。
使用项出口商¶
如果你很匆忙,只想使用项目导出器输出抓取的数据,请参阅 饲料出口。否则,如果您想知道项出口商如何工作或需要更多的自定义功能(不包括在默认导出),请继续阅读下面。
为了使用项目导出程序,您必须使用其必需的参数实例化它。每个项目导出程序需要不同的参数,因此请在 内置物料出口商参考 中检查每个导出程序文档以确保。在您实例化您的出口商后,您必须:
1. call the method start_exporting()
in order to
signal the beginning of the exporting process
2. call the export_item()
method for each item you want
to export
3. and finally call the finish_exporting()
to signal
the end of the exporting process
在这里,您可以看到一个 项目管道,它使用项目导出器将刮取的项目导出到不同的文件,每个蜘蛛一个:
from scrapy import signals
from scrapy.exporters import XmlItemExporter
class XmlExportPipeline(object):
def __init__(self):
self.files = {}
@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('%s_products.xml' % spider.name, 'w+b')
self.files[spider] = file
self.exporter = XmlItemExporter(file)
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
项目字段的序列化¶
默认情况下,字段值未修改地传递给底层序列化库,并且如何将它们序列化的决定被委托给每个特定的序列化库。
但是,您可以自定义每个字段值如何序列化 之前它被传递到序列化库。
有两种方法来定制字段将如何被序列化,这将在下面描述。
1. Declaring a serializer in the field¶
如果您使用 Item
,您可以在 字段元数据 中声明一个序列化程序。序列化程序必须是一个可调用,它接收一个值并返回它的序列化形式。
例:
import scrapy
def serialize_price(value):
return '$ %s' % str(value)
class Product(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field(serializer=serialize_price)
2. Overriding the serialize_field() method¶
您还可以覆盖 serialize_field()
方法以自定义字段值的导出方式。
请确保在您的自定义代码后调用基类 serialize_field()
方法。
例:
from scrapy.exporter import XmlItemExporter
class ProductXmlExporter(XmlItemExporter):
def serialize_field(self, field, name, value):
if field == 'price':
return '$ %s' % str(value)
return super(Product, self).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')¶ 这是所有项出口商的(抽象)基类。它为所有(具体)项出口商使用的通用功能提供支持,例如定义要导出的字段,是否导出空字段或要使用的编码。
这些特性可以通过构造函数参数配置,构造函数参数填充它们各自的实例属性:
fields_to_export
,export_empty_fields
,encoding
。-
export_item
(item)¶ 导出给定项目。此方法必须在子类中实现。
-
serialize_field
(field, name, value)¶ 返回给定字段的序列化值。如果要控制特定字段或值将如何序列化/导出,您可以覆盖此方法(在自定义项出口商中)。
默认情况下,此方法查找序列化程序 在项目字段中声明 并返回将该序列化程序应用于该值的结果。如果没有找到序列化器,它将返回除
unicode
值之外的其他值,这些值使用encoding
属性中声明的编码编码为str
。参数:
-
start_exporting
()¶ 表示导出过程的开始。一些导出器可以使用它来生成一些必需的头(例如,
XmlItemExporter
)。您必须在导出任何项目之前调用此方法。
-
finish_exporting
()¶ 表示导出过程结束。一些出口商可能使用它来生成一些必需的页脚(例如,
XmlItemExporter
)。在没有更多项目要导出之后,必须始终调用此方法。
-
fields_to_export
¶ 包含要导出字段名称的列表,如果要导出所有字段,则为无。默认为无。
一些导出器(如
CsvItemExporter
)遵循此属性中定义的字段的顺序。一些导出器可能需要fields_to_export列表,以便在蜘蛛返回dicts时(不是
Item
实例)正确导出数据。
-
export_empty_fields
¶ 是否在导出的数据中包含空/未填充的项目字段。默认为
False
。一些导出器(如CsvItemExporter
)忽略此属性,并始终导出所有空字段。对于dict项,忽略此选项。
-
encoding
¶ 将用于编码unicode值的编码。这只影响unicode值(总是使用此编码序列化为str)。其他值类型不变地传递到特定的序列化库。
-
XmlItemExporter¶
-
class
scrapy.exporters.
XmlItemExporter
(file, item_element='item', root_element='items', **kwargs)¶ 将XML格式的项目导出到指定的文件对象。
参数: - file – 用于导出数据的类文件对象。
- root_element (str) – 导出的XML中根元素的名称。
- item_element (str) – 导出的XML中每个项目元素的名称。
此构造函数的其他关键字参数传递给
BaseItemExporter
构造函数。这个出口商的典型输出是:
<?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=', ', **kwargs)¶ 将CSV格式的项目导出到给定的类文件对象。如果设置了
fields_to_export
属性,它将用于定义CSV列及其顺序。export_empty_fields
属性对此导出器没有影响。参数: - file – 用于导出数据的类文件对象。
- include_headers_line (str) – 如果启用,则使输出器输出标题行,其字段名称取自
BaseItemExporter.fields_to_export
或第一个导出的项目字段。 - join_multivalued – 将用于加入多值字段(如果找到)的char(或chars)。
此构造函数的附加关键字参数传递给
BaseItemExporter
构造函数,并将剩余参数传递给 csv.writer 构造函数,因此您可以使用任何 csv.writer 构造函数参数来自定义此导出器。这个出口商的典型输出是:
product,price Color TV,1200 DVD player,200
PickleItemExporter¶
-
class
scrapy.exporters.
PickleItemExporter
(file, protocol=0, **kwargs)¶ 将pickle格式的项目导出到给定的类文件对象。
参数: - file – 用于导出数据的类文件对象。
- protocol (int) – 使用pickle协议。
有关详细信息,请参阅 pickle module documentation。
此构造函数的其他关键字参数传递给
BaseItemExporter
构造函数。Pickle不是一个人类可读的格式,所以没有提供输出示例。
PprintItemExporter¶
-
class
scrapy.exporters.
PprintItemExporter
(file, **kwargs)¶ 将美观打印格式的项目导出到指定的文件对象。
参数: file – 用于导出数据的类文件对象。 此构造函数的其他关键字参数传递给
BaseItemExporter
构造函数。这个出口商的典型输出是:
{'name': 'Color TV', 'price': '1200'} {'name': 'DVD player', 'price': '200'}
较长的行(如果存在)是漂亮的格式。
JsonItemExporter¶
-
class
scrapy.exporters.
JsonItemExporter
(file, **kwargs)¶ 将JSON格式的项导出到指定的类文件对象,将所有对象写为对象列表。附加的构造函数参数传递给
BaseItemExporter
构造函数,剩余参数传递给 JSONEncoder 构造函数,因此您可以使用任何 JSONEncoder 构造函数参数来自定义此导出器。参数: file – 用于导出数据的类文件对象。 这个出口商的典型输出是:
[{"name": "Color TV", "price": "1200"}, {"name": "DVD player", "price": "200"}]
警告
JSON是非常简单和灵活的序列化格式,但它不能很好地扩展大量的数据,因为增量(也称为流模式)解析在JSON解析器(任何语言)不能很好地支持(如果有)大多数人只是解析内存中的整个对象。如果您希望JSON的功能和简单性与更友好的流格式,请考虑使用
JsonLinesItemExporter
,或将输出拆分为多个块。
JsonLinesItemExporter¶
-
class
scrapy.exporters.
JsonLinesItemExporter
(file, **kwargs)¶ 将JSON格式的项目导出到指定的类文件对象,每行写一个JSON编码的项目。附加的构造函数参数传递给
BaseItemExporter
构造函数,剩余参数传递给 JSONEncoder 构造函数,因此您可以使用任何 JSONEncoder 构造函数参数来自定义此导出器。参数: file – 用于导出数据的类文件对象。 这个出口商的典型输出是:
{"name": "Color TV", "price": "1200"} {"name": "DVD player", "price": "200"}
与
JsonItemExporter
生成的不同,该导出器生成的格式非常适合于序列化大量数据。