请求返回字节,我无法解码它们

2024-05-18 14:29:50 发布

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

实际上,我向一个网站发出了一个请求,并得到了一个字节响应:b'[{"geonameId:"703448"}..........'.我很困惑,因为虽然它是byte类型的,但它是非常可读的,看起来像一个json列表。我知道响应是在运行r.encoding(返回ISO-859-1)时用latin1编码的,我试图对其进行解码,但它只返回一个空字符串。以下是我目前掌握的情况:

r = response.content
string = r.decode("ISO-8859-1")
print (string)

这是它打印空白行的地方。 但是当我跑的时候

len(string)

我得到:返回31023 如何在不返回空字符串的情况下解码这些字节?


Tags: 字符串json类型列表string字节网站情况
3条回答

r.textr.content。第一个是字符串,第二个是字节。

你想要的

import json

data = json.loads(r.text)

你试过用json模块解析它吗?

import json
parsed = json.loads(response.content)

另一个解决方案是使用response.text,它以unicode格式返回内容

Type:        property
String form: <property object at 0x7f76f8c79db8>
Docstring:  
Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using
``chardet``.

The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.

相关问题 更多 >

    热门问题