在Python2.7中打开URL时返回了乱码文本

2024-04-25 04:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打开stackexchangeapi(搜索端点)URL并解析结果[0]。文档中说,所有结果都是JSON格式的[1]。我在我的网络浏览器中打开这个网址,结果绝对不错[2]。但是,当我尝试使用Python程序打开它时,它返回了我无法解析的编码文本。这是一个剪报

á¬ôŸ?ÍøäÅ€ˆËç?bçÞIË
¡ëf)j´ñ‚TF8¯KÚpr®´Ö©iUizEÚD +¦¯÷tgNÈÑ.G¾LPUç?Ñ‘Ù~]ŒäÖÂ9Ÿð1£µ$JNóa?Z&Ÿtž'³Ðà#Í°¬õÅj5ŸE÷*æJî”Ï>íÓé’çÔqQI’†ksS™¾þEíqÝýly

我的程序打开一个网址如下。我到底做错了什么?在

^{pr2}$

[0]https://api.stackexchange.com/2.1/search/advanced?page=1&pagesize=100&order=desc&sort=relevance&q=openRawResource%2C+AssetManager.AssetInputStream+throws+IOException+on+read+of+larger+files&site=stackoverflow&access_token=*****&key=*****

[1]https://api.stackexchange.com/docs

[2]http://hastebin.com/qoxaxahaxa.sm

苏尔特

我找到了解决办法。下面是你应该怎么做。在

request = urllib2.Request(query)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO( response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()
    result = json.loads(data)

不能发布完整的输出,因为它也是很大。很多感谢Evert和Kristaps指出了关于解压和设置请求头的信息。此外,还有一个类似的问题需要研究[3]。在

[3]Does python urllib2 automatically uncompress gzip data fetched from webpage?


Tags: https程序comapireaddataresponserequest
2条回答

文件的下一段说:

Additionally, all API responses are compressed. The Content-Encoding header is always set, but some proxies will strip this out. The proper way to decode API responses can be found here.

你的输出看起来像是被压缩了。浏览器会自动解压缩数据(取决于内容编码),因此您需要查看头并执行相同的操作:results = json.loads(zlib.decompress(text))或类似的操作。在

也要检查here链接。在

我找到了解决办法。下面是你应该怎么做。在

request = urllib2.Request(query)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO( response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()
    result = json.loads(data)

不能发布完整的输出,因为它也是很大。很多感谢Evert和Kristaps指出了关于解压和设置请求头的信息。此外,还有一个类似的问题需要研究[1]。在

[1]Does python urllib2 automatically uncompress gzip data fetched from webpage?

相关问题 更多 >