Scrapy输出中文保存中文

scrapy在保存json文件时容易乱码

settings.py文件改动:
ITEM_PIPELINES = {
   'tutorial.pipelines.TutorialPipeline': 300,
}
pipeline.py文件改动:
import json
import codecs

class TutorialPipeline(object):
    def open_spider(self, spider):
        self.file = codecs.open('data_cn.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + '\n'
        self.file.write(line)
        return item

    def close_spider(self, spider)
        self.file.close()

留下评论