zoukankan      html  css  js  c++  java
  • 解决Scrapy抓取中文网页保存为json文件时中文不显示而是显示unicode的问题

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

    情境再现:

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

    {'author': u'u51afu53cbu5170u7b49',
     'classification': u' u4ebau6587u793eu79d1',
     'down_bd_code': u'u63d0u53d6u5bc6u7801uff1asp6t',
     'down_bd_url': u'https://pan.baidu.com/s/1N1NPVupmnPX6W5Fm2YHccg',
     'title': u'u4e2du897fu65b9u54f2u5b66u53f2uff08u5957u88c5u51712u518cuff09'}

    保存成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) + '
    '
            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文件

  • 相关阅读:
    SQlite数据库
    关于如何获取剪切板的多个图片处理
    aes 和 Md5 分析
    SIP消息
    getItemAt
    C++ map的方法
    C++ 解析Json
    CentOS 6.3安装配置LAMP服务器(Apache+PHP5+MySQL)
    阿里云服务器CentOS 5.7(64位)安装配置LAMP服务器(Apache+PHP5+MySQL)
    Apache虚拟主机(vhost)配置教程
  • 原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/10309401.html
Copyright © 2011-2022 走看看