0
import json
import urllib2
url = "http://api.douban.com/v2/book/1220562"
hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
req = urllib2.Request(url, headers=hdr)
html = urllib2.urlopen(req).read()
html = json.loads(html)
func_name = 'callback'
html = '{0}({1})'.format(func_name, html)
print html

输出:

callback({u'rating': {u'max': 10, u'numRaters': 310, u'average': u'7.0', u'min': 0}, u'subtitle': u'', u'pubdate': u'2005-1', u'image': u'http://img3.douban.com/mpic/s1747553.jpg', u'binding': u'\u5e73\u88c5',..............})

我想将输出编码为 gb2312 或使其更好的东西。也许像

callback({'rating': {'max': 10, 'numRaters': 310, 'average': '7.0', 'min': 0......})

示例输出:url

4

2 回答 2

1

您的问题与编码无关,至少目前还没有。

您正在使用 将 dict 转换为字符串'{0}({1})'.format(func_name, html)

您应该使用 json.dumps 将 python 对象转换为 json 字符串。

json.dumps有一个ensure_ascii默认值为 True 的参数。它使用 \uXXXX 序列转义输出中的所有非 ASCII 字符,结果是一个仅由 ASCII 字符组成的 str 实例。如果 ensure_ascii 为 False,则结果可能包含非 ASCII 字符,返回值可能是 unicode 实例。

json.dumps(html, ensure_ascii=False)
于 2013-11-13T05:20:33.480 回答
1

考虑切换到 Python 3,它将显示非 ASCII 字符而不是 Unicode 代码点。2to3.py我通过Python 安装目录中可用的转换器运行您的代码Tools\Scripts,然后添加了 UTF-8 解码和漂亮的打印:

import json
import urllib.request, urllib.error, urllib.parse
import pprint
url = "http://api.douban.com/v2/book/1220562"
hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
req = urllib.request.Request(url, headers=hdr)
html = urllib.request.urlopen(req).read().decode('utf8')
html = json.loads(html)
pprint.pprint(html)

在支持中文的合适终端或IDE上输出:

{'alt': 'http://book.douban.com/subject/1220562/',
 'alt_title': '',
 'author': ['[日] 片山恭一'],
 'author_intro': '',
 'binding': '平装',
 'catalog': '\n      ',
 'id': '1220562',
 'image': 'http://img3.douban.com/mpic/s1747553.jpg',
 'images': {'large': 'http://img3.douban.com/lpic/s1747553.jpg',
            'medium': 'http://img3.douban.com/mpic/s1747553.jpg',
            'small': 'http://img3.douban.com/spic/s1747553.jpg'},
 'isbn10': '7543632608',
 'isbn13': '9787543632608',
 'origin_title': '',
 'pages': '180',
 'price': '15.00元',
 'pubdate': '2005-1',
 'publisher': '青岛出版社',
 'rating': {'average': '7.0', 'max': 10, 'min': 0, 'numRaters': 310},
 'subtitle': '',
 'summary': '那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。',
 'tags': [{'count': 120, 'name': '片山恭一', 'title': '片山恭一'},
          {'count': 57, 'name': '日本', 'title': '日本'},
          {'count': 50, 'name': '日本文学', 'title': '日本文学'},
          {'count': 33, 'name': '小说', 'title': '小说'},
          {'count': 31, 'name': '满月之夜白鲸现', 'title': '满月之夜白鲸现'},
          {'count': 11, 'name': '爱情', 'title': '爱情'},
          {'count': 8, 'name': '外国文学', 'title': '外国文学'},
          {'count': 7, 'name': '純愛', 'title': '純愛'}],
 'title': '满月之夜白鲸现',
 'translator': ['豫人'],
 'url': 'http://api.douban.com/v2/book/1220562'}
于 2013-11-13T06:53:11.940 回答