python2.7打印接口返回的数据时提示[Decode error - output not utf-8]
阿神
阿神 2017-04-17 17:35:45
0
3
450

打印接口返回的数据,提示[Decode error - output not utf-8]

代码如下:

-- coding=utf-8 --

import urllib2
import json
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

html = urllib2.urlopen(r'http://api.douban.com/v2/book/isbn/9787218087351')
content=html.read()
content = content.decode('UTF-8')
hjson = json.loads(content)

print u' '

print hjson['rating']

print hjson'images'

print hjson['summary']

如果不注释上图圈的一行代码就能正常打印。新手小白请大神指教

阿神
阿神

闭关修行中......

reply all(3)
伊谢尔伦

This has something to do with the sublime terminal. It may only support utf-8. Because the content in your hjson is unicode, it is not supported when printed. Try encoding it as utf-8:

 print hjson['summary'].encode('utf-8')
伊谢尔伦

Regarding the issue with Sublime, please try running the program on the command line first to see if there will be an error. Sublime的问题,你先试试在命令行里执行程序会不会报错。

命令行正常的话,这个应该是中文导致的编码问题,你看下你的Sublime的文件默认编码,左下角或者右下角有写,如果不是utf-8,就改成utf-8

If the command line is normal, this should be an encoding problem caused by Chinese. Check the default encoding of your Sublime file. It is written in the lower left or lower right corner. If it is not utf-8, try changing it to utf-8. 🎜
Peter_Zhu

coding=utf-8

import requests, json
r = requests.get('http://api.douban.com/v2/book/isbn/9787218087351')
obj = json.loads(r.text)
print obj['summary']

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!