解决Scrapy抓取中文结果保存为文件时的编码问题

时间:2023-03-08 20:22:36
 import json
import codecs # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class PandaPipeline(object):
def __init__(self):
self.file = codecs.open('pandaow.json', 'w', encoding='utf-8') def process_item(self, item, spider):
line = json.dumps(dict(item),ensure_ascii=False) + '\n'
# print line
# self.file.write(line.decode("unicode_escape"))
self.file.write(line)
return item def spider_closed(self, spider):
self.file.close()

将以上内容插入pipelines.py,同时在settings.py中加入

ITEM_PIPELINES = {
'panda.pipelines.PandaPipeline': 300
}

以调用pipelines文件