我想打开 StackExchange API(搜索端点)URL 并解析结果 [0]。文档说所有结果都是 JSON 格式 [1]。我在网络浏览器中打开这个 URL,结果非常好 [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
我打开URL的程序如下。我做错了什么特别错误?
''' Opens a URL and returns the result '''
def open_url(query):
request = urllib2.Request(query)
response = urllib2.urlopen(request)
text = response.read()
#results = json.loads(text)
print text
title = openRawResource, AssetManager.AssetInputStream throws IOException on read of larger files
page1_query = stackoverflow_search_endpoint % (1,urllib.quote_plus(title),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 指出有关解压和设置请求 header 的信息。此外,人们还想研究另一个类似的问题[3]。
[3] Does python urllib2 automatically uncompress gzip data fetched from webpage?
最佳答案
文档的下一段说:
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.
您的输出看起来确实可能被压缩。浏览器会自动解压缩数据(取决于内容编码),因此您需要查看 header 并执行相同的操作:results = json.loads(zlib.decompress(text))
或类似的内容.
也请检查此处
链接。
关于python - 在 Python 2.7 中打开 URL 时返回乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670711/