解决Scrapy抓取中文网页保存为json文件时中文不显示而是显示unicode的问题

注意:此方法跟之前保存成json文件的写法有少许不同之处,注意区分

情境再现:

使用scrapy抓取中文网页,得到的数据类型是unicode,在控制台输出的话也是显示unicode,如下所示

{'author': u'\u51af\u53cb\u5170\u7b49',
 'classification': u' \u4eba\u6587\u793e\u79d1',
 'down_bd_code': u'\u63d0\u53d6\u5bc6\u7801\uff1asp6t',
 'down_bd_url': u'https://pan.baidu.com/s/1N1NPVupmnPX6W5Fm2YHccg',
 'title': u'\u4e2d\u897f\u65b9\u54f2\u5b66\u53f2\uff08\u5957\u88c5\u51712\u518c\uff09'}

保存成json文件时需要显示出中文

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 WriteJsonPipeline(object):
    def __init__(self):
        self.file = codecs.open('items.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 spider_closed(self, spider):
        self.file.close()

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

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

以调用pipelines文件

猜你喜欢

转载自www.cnblogs.com/sanduzxcvbnm/p/10309401.html