Scrapy 數(shù)據(jù)保存到j(luò)son
創(chuàng)建json保存的pipeline
pipeline處理
import codecs
這個包可以處理好編碼摩泪,避免各種編碼繁雜工作涕蚤。
新建pipeline,構(gòu)造函數(shù) codecs打開文件,用'w'的方式周叮。
class JsonWithEncodingPipeline(object):
def __init__(self):
self.file = codecs.open('article.json', 'w', encoding="utf-8")
第二骇钦,像下面的方式一樣處理pipeline宛渐。
class ArticlespiderPipeline(object):
def process_item(self, item, spider):
item不是dict,但是?可以用dict(item)
轉(zhuǎn)化成dict眯搭。因為直接json.dumps(item)
是不行的窥翩,所以要用dict()轉(zhuǎn)化。
def process_item(self, item, spider):
lines = json.dumps(dict(item), ensure_ascii=False, )
其中ensure_ascii=False
一定要False鳞仙,否則導(dǎo)入中文會不正常寇蚊。
寫入文件并返回item。
def process_item(self, item, spider):
lines = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(lines)
return item
關(guān)閉爬蟲時棍好,關(guān)閉文件仗岸。
def spider_closed(self, spider):
self.file.close()
配置pipeline
ITEM_PIPELINES = {
'ArticleSpider.pipelines.ArticleImagePipeline': 1,
'ArticleSpider.pipelines.JsonWithEncodingPipeline':2,
}
Scrapy自帶寫入json
在pipeline中,
from scrapy.exporters import JsonItemExporter
進入函數(shù)借笙,最上面可以看見有多種格式的導(dǎo)出方式扒怖。
wb
二進制方式打開。
class JsonExporterPipeline(object):
# 調(diào)用Scrapy提供的JsonExporter導(dǎo)出Json文件业稼。
def __init__(self):
self.file = open('article_exporter.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
json中前后都有括號盗痒,是因為exporter.py中前后都加了括號。
def start_exporting(self):
self.file.write(b"[\n")
def finish_exporting(self):
self.file.write(b"\n]")