到中文字符JSON的scrapy管道

时间:2018-11-20 14:41:11

标签: 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字符:)

1 个答案:

答案 0 :(得分:1)

似乎json库转义了这些符号,请尝试将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