1. 修改settings.py,啟用item pipelines組件
將
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
# ITEM_PIPELINES = {
# 'tutorial.pipelines.TutorialPipeline': 300,
# }
改為
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'tutorial.pipelines.TutorialPipeline': 300,
}
當然,我們不能只改而不去研究其中的意義.
根據官方注釋我們順利找到了官方文檔對此的解釋說明:
為了啟用一個Item Pipeline組件,你必須將它的類添加到
ITEM_PIPELINES
配置,就像下面這個例子:ITEM_PIPELINES = { 'myproject.pipelines.PricePipeline': 300, 'myproject.pipelines.JsonWriterPipeline': 800, >}
分配給每個類的整型值,確定了他們運行的順序,item按數字從低到高的順序,通過pipeline,通常將這些數字定義在0-1000范圍內。
那么什么是Item Pipeline組件呢?
當Item在Spider中被收集之后,它將會被傳遞到Item Pipeline,一些組件會按照一定的順序執行對Item的處理。
每個item pipeline組件(有時稱之為“Item Pipeline”)是實現了簡單方法的Python類。他們接收到Item並通過它執行一些行為,同時也決定此Item是否繼續通過pipeline,或是被丟棄而不再進行處理。
以下是item pipeline的一些典型應用:
- 清理HTML數據
- 驗證爬取的數據(檢查item包含某些字段)
- 查重(並丟棄)
- 將爬取結果保存到數據庫中
如果你想了解更多item pipeline組件相關的知識,請自行閱讀官方文檔
2.設置item pipelines組件
將你的 *pipelines.py 代碼添加以下代碼
def *_item(self, item, spider):
with open('data_cn1.json', 'a') as f:
json.dump(dict(item), f, ensure_ascii=False)
f.write(',\n')
return item
其中重點關注一下json.dump函數
根據查看json的源碼中的注釋發現:
If
ensure_ascii
is false, then the strings written tofp
can
contain non-ASCII characters if they appear in strings contained in
obj
. Otherwise, all such characters are escaped in JSON strings.
如果ensure_ascii
為false,那么寫入fp
的字符串可以包含非ASCII字符。否則,所有這些字符都會在JSON字符串中轉義。
也就是說json.dump函數將獲取到item轉化成字符串中存入json文件,並且 將參數ensure_ascii設為False使得中文(UTF-8編碼)不經過轉義,也就不會亂碼
參考: