當(dāng)你抓取了你要的數(shù)據(jù)(Items),你就會(huì)想要將他們持久化或?qū)С鏊鼈儯?yīng)用在其他的程序。這是整個(gè)抓取過程的目的。
為此,Scrapy 提供了 Item Exporters 來創(chuàng)建不同的輸出格式,如 XML,CSV 或 JSON。
如果你很忙,只想使用 Item Exporter 輸出數(shù)據(jù),請查看 Feed exports。相反,如果你想知道 Item Exporter 是如何工作的,或需要更多的自定義功能(不包括默認(rèn)的 exports),請繼續(xù)閱讀下文。
為了使用 Item Exporter,你必須對 Item Exporter 及其參數(shù) (args) 實(shí)例化。每個(gè) Item Exporter 需要不同的參數(shù),詳細(xì)請查看 Item Exporters 參考資料
。在實(shí)例化了 exporter 之后,你必須:
start_exporting()
以標(biāo)識 exporting 過程的開始。export_item()
方法。finish_exporting()
表示 exporting 過程的結(jié)束這里,你可以看到一個(gè) Item Pipeline,它使用 Item Exporter 導(dǎo)出 items 到不同的文件,每個(gè) spider 一個(gè):
from scrapy import signals
from scrapy.contrib.exporter 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
序列化 item fields
B 默認(rèn)情況下,該字段值將不變的傳遞到序列化庫,如何對其進(jìn)行序列化的決定被委托給每一個(gè)特定的序列化庫。
但是,你可以自定義每個(gè)字段值如何序列化在它被傳遞到序列化庫中之前。
有兩種方法可以自定義一個(gè)字段如何被序列化,請看下文。
您可以在 field metadata 聲明一個(gè) serializer。該 serializer 必須可調(diào)用,并返回它的序列化形式。
實(shí)例:
import scrapy
def serialize_price(value):
return '$ %s' % str(value)
class Product(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field(serializer=serialize_price)
你可以覆蓋 serialize_field()
方法來自定義如何輸出你的數(shù)據(jù)。
在你的自定義代碼后確保你調(diào)用父類的 serialize_field()
方法。
實(shí)例:
from scrapy.contrib.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 內(nèi)置的 Item Exporters 類. 其中一些包括了實(shí)例, 假設(shè)你要輸出以下 2 個(gè) Items:
Item(name='Color TV', price='1200')
Item(name='DVD player', price='200')
這是一個(gè)對所有 Item Exporters 的(抽象)父類。它對所有(具體) Item Exporters 提供基本屬性,如定義 export 什么 fields, 是否 export 空 fields, 或是否進(jìn)行編碼。
你可以在構(gòu)造器中設(shè)置它們不同的屬性值:fields_to_export
,export_empty_fields
, encoding
。
輸出給定 item。此方法必須在子類中實(shí)現(xiàn)。
返回給定 field 的序列化值。你可以覆蓋此方法來控制序列化或輸出指定的 field。
默認(rèn)情況下,此方法尋找一個(gè) serializer 在 item field
中聲明 并返回它的值。如果沒有發(fā)現(xiàn) serializer,則值不會(huì)改變,除非你使用 unicode 值并編碼到 str,編碼可以在 encoding
屬性中聲明。
參數(shù):
Field
object) – the field being serialized表示 exporting 過程的開始。一些 exporters 用于產(chǎn)生需要的頭元素(例如 XmlItemExporter
)。 在實(shí)現(xiàn) exporting item 前必須調(diào)用此方法。
表示 exporting 過程的結(jié)束。一些 exporters 用于產(chǎn)生需要的尾元素 (例如 XmlItemExporter
)。 在完成 exporting item 后必須調(diào)用此方法。
列出 export 什么 fields 值,None 表示 export 所有 fields。默認(rèn)值為 None。
一些 exporters (例如 CsvItemExporter
) 按照定義在屬性中 fields 的次序依次輸出。
是否在輸出數(shù)據(jù)中包含為空的 item fields。默認(rèn)值是 False。一些 exporters (例如 CsvItemExporter) 會(huì)忽略此屬性并輸出所有 fields。
Encoding 屬性將用于編碼 unicode 值。(僅用于序列化字符串)。其他值類型將不變的傳遞到指定的序列化庫。
以 XML 格式 exports Items 到指定的文件類。
參數(shù):
構(gòu)造器額外的關(guān)鍵字參數(shù)將傳給 BaseItemExporter
構(gòu)造器。
一個(gè)典型的 exporter 實(shí)例:
<?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()
方法,多個(gè)值的 fields 會(huì)轉(zhuǎn)化每個(gè)值到<value>
元素。
例如,item:
Item(name=['John', 'Doe'], age='23')
將被轉(zhuǎn)化為:
<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<name>
<value>John</value>
<value>Doe</value>
</name>
<age>23</age>
</item>
</items>
輸出 csv 文件格式。如果添加 fields_to_export
屬性,它會(huì)按順序定義 CSV 的列名。 export_empty_fields
屬性在此沒有作用。
參數(shù):
BaseItemExporter.fields_to_export
或第一個(gè) item fields 獲取。此構(gòu)造器額外的關(guān)鍵字參數(shù)將傳給 BaseItemExporter
構(gòu)造器,其余的將傳給 csv.writer 構(gòu)造器, 以此來定制 exporter。
一個(gè)典型的 exporter 實(shí)例:
product,price
Color TV,1200
DVD player,200
輸出 pickle 文件格式。
參數(shù):
更多信息請看 pickle module documentation。
此構(gòu)造器額外的關(guān)鍵字參數(shù)將傳給 BaseItemExporter 構(gòu)造器。
Pickle 不是可讀的格式,這里不提供實(shí)例。
輸出整齊打印的文件格式。
參數(shù):
此構(gòu)造器額外的關(guān)鍵字參數(shù)將傳給 BaseItemExporter 構(gòu)造器。
一個(gè)典型的 exporter 實(shí)例:
{'name': 'Color TV', 'price': '1200'}
{'name': 'DVD player', 'price': '200'}
此格式會(huì)根據(jù)行的長短進(jìn)行調(diào)整。
輸出 JSON 文件格式,所有對象將寫進(jìn)一個(gè)對象的列表。此構(gòu)造器額外的關(guān)鍵字參數(shù)將傳給 BaseItemExporter
構(gòu)造器,其余的將傳給 JSONEncoder 構(gòu)造器,以此來定制 exporter。
參數(shù):
一個(gè)典型的 exporter 實(shí)例:
[{"name": "Color TV", "price": "1200"},
{"name": "DVD player", "price": "200"}]
警告
JSON 是一個(gè)簡單而有彈性的格式, 但對大量數(shù)據(jù)的擴(kuò)展性不是很好,因?yàn)檫@里會(huì)將整個(gè)對象放入內(nèi)存。如果你要 JSON 既強(qiáng)大又簡單,可以考慮 JsonLinesItemExporter
,或把輸出對象分為多個(gè)塊。
輸出 JSON 文件格式, 每行寫一個(gè) JSON-encoded 項(xiàng)。此構(gòu)造器額外的關(guān)鍵字參數(shù)將傳給 BaseItemExporter
構(gòu)造器,其余的將傳給 JSONEncoder 構(gòu)造器,以此來定制 exporter。
參數(shù):
一個(gè)典型的 exporter 實(shí)例:
{"name": "Color TV", "price": "1200"}
{"name": "DVD player", "price": "200"}
這個(gè)類能很好的處理大量數(shù)據(jù)。