python - 带有中文字符的 JSON 的 scrapy 管道

标签 python json scrapy

我正在尝试抓取一些带有中文字符的网页内容。内容如下所示

2018-11-20 12:42:18 [scrapy.core.scraper] DEBUG: Scraped from <200  https://cn.bing.com/dict/search?q=tool&FORM=BDVSP6&mkt=zh-cn>
{'defBing': '工具;方法;受人利用的人',
 'defWeb': '工具;方法;受人利用的人',
 'pClass': 'n.',
 'prUK': 'UK\xa0[tuːl]',
 'prUS': 'US\xa0[tul]',
 'word': 'tool'}

但是经过流水线处理后,内容变成了这样:

{
    "word": "tool",
    "prUS": "US\u00a0[tul]",
    "prUK": "UK\u00a0[tu\u02d0l]",
    "pClass": "n.",
    "defBing": "\u5de5\u5177\uff1b\u65b9\u6cd5\uff1b\u53d7\u4eba\u5229\u7528\u7684\u4eba",
    "defWeb": "\u5de5\u5177\uff1b\u65b9\u6cd5\uff1b\u53d7\u4eba\u5229\u7528\u7684\u4eba"
}

管道看起来像:

class JsonWriterPipeline(object):
    def open_spider(self, spider):
        self.file = open('log/DICT.%s.json' % time.strftime('%Y%m%d-%H%M%S', time.localtime()), 'tw')

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

    def process_item(self, item, spider):
        try:
            line = json.dumps(dict(item), indent=4) + "\n"
            self.file.write(line)
        except Exception as e:
            print(e)
        return item

我的问题是:如何在 *.json 文件中保持汉字原样打印?我真的不想要那些编码的 Unicode 字符:)

最佳答案

似乎 json lib 转义了这些符号,尝试将 ensure_ascii=False 添加到 json.dumps() 中,如下所示:

class JsonWriterPipeline(object):
    def open_spider(self, spider):
        self.file = open('log/DICT.%s.json' % time.strftime('%Y%m%d-%H%M%S', time.localtime()), 'tw')

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

    def process_item(self, item, spider):
        try:
            line = json.dumps(dict(item), indent=4, ensure_ascii=False) + "\n"
            self.file.write(line)
        except Exception as e:
            print(e)
        return item

关于python - 带有中文字符的 JSON 的 scrapy 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395450/

相关文章:

python - TensorFlow 使用 tf.while_loop() 陷入无限循环

python - Ubuntu升级操作系统安装的python包

python - 如何在没有 csv 索引 header 的情况下编写行?

python - 获取数据框中所有列的平均值并创建一个新数据框

json - 使用 Axios 从 Laravel Controller 捕获错误

json - 当键在 Powershell 中包含点(句点)时从 JSON 解析值

php - 如何用PHP和MySQL创建JSON嵌套子父树(PDO方法)

python - scrapy教程运行爬虫时出错

python - 抓取和监控 +1000 个网站

python - ScraPy蜘蛛爬行但不导出