在Scrapy中,所有item數(shù)據(jù)都會(huì)通過(guò)pipelines進(jìn)行處理,想要保存為json格式文件,只需要在piplines中進(jìn)行相應(yīng)的處理即可。
1、使用系統(tǒng)模塊導(dǎo)出json
from scrapy.exporters import JsonItemExporter
class JsonExporterPipeline(object):
def __init__(self):
self.file = open('articlejson.json', 'wb')
self.exporter = JsonItemExporter(self.file, encoding="utf-8", ensure_ascii=False)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
2、自定義
在pipelines.py中加入以下代碼
import codecs
import json
class JsonWithEncodingPipeline(object):
def __init__(self):
self.file = codecs.open('article.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
lines = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(lines)
return item
def spider_closed(self, spider):
self.file.close()
說(shuō)明:
codecs避免打開文件時(shí)出現(xiàn)編碼錯(cuò)誤。
json.dumps: dict轉(zhuǎn)成str
json.loads: str轉(zhuǎn)成dict
ensure_ascii=False: 避免處理英文以外語(yǔ)言時(shí)出錯(cuò)
return item:交給下一個(gè)pipeline處理