打印接口返回的数据,提示[Decode error - output not 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 hjson['summary']
如果不注释上图圈的一行代码就能正常打印。新手小白请大神指教
伊谢尔伦2017-04-17 17:37:45
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')
伊谢尔伦2017-04-17 17:37:45
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
Sublime
file. It is written in the lower left or lower right corner. If it is not utf-8< /code>, try changing it to utf-8
. 🎜reply0
天蓬老师2017-04-17 17:37:45
import requests, json
r = requests.get('http://api.douban.com/v2/book/isbn/9787218087351')
obj = json.loads(r.text)
print obj['summary']