Reputation: 201
I'm trying to scrapy some web contents with Chinese character. the content scraped like below
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'}
But after the pipeline process, the content has been like this:
{
"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"
}
The pipeline looks like:
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
my question is: how can I keep the Chinese character printed as-is in the *.json file? I really don't want those encoded Unicode characters :)
Upvotes: 2
Views: 265
Reputation: 2545
It seems like the json lib escape those symbols, try to add ensure_ascii=False
to json.dumps()
as follow:
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
Upvotes: 1