python - 在 Python 2.7 中打开 URL 时返回乱码

标签 python json python-2.7 urllib2 urlencode

我想打开 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)

[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= ******&键=******

[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/

相关文章:

javascript - 有没有办法强制 Node 使用 Unicode 字符的代理对(JSON 格式)写入文件?

json - 通过json发送expressjs cookie

python - 在 account.move 上使用银行帐户作为 account_id - Odoo v8

python - 如何安装mysql连接器

python - 处理 Python 中可以 str 或 list 的函数参数

python - 如何迭代解析 zipfile 对象

Python 查询游戏服务器

json - 如何检查 JWT 的角色声明(值数组)的某个值?

python-2.7 - 注册到 PyPi : basic auth failed

python-2.7 - 用 BeautifulSoup 替换 python 中的文本