Python爬蟲學(xué)習(xí)12-爬取數(shù)據(jù)保存為json

在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處理

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容