【问题标题】:Request returns bytes and I'm failing to decode them请求返回字节,我无法解码它们
【发布时间】:2015-10-20 21:50:55
【问题描述】:

基本上我向网站发出请求并得到一个字节响应:b'[{"geonameId:"703448"}..........'. 我很困惑,因为虽然它是字节类型,但它非常易于人类阅读,并且看起来像一个 json 列表。我知道响应是在运行r.encoding 时以latin1 编码的,它返回ISO-859-1,我试图对其进行解码,但它只返回一个空字符串。这是我目前所拥有的:

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

这是它打印一个空行的地方。 但是,当我运行

len(string)

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

【问题讨论】:

  • 在 python 2.x 中,b 前缀将导致包含的字符串成为str 类型,您可能已经隐藏了一些编码字符。在 Python 3.x 上,您将收到 bytes 文字。为什么你认为你需要执行任何编码/解码?
  • 因为我需要解析 json,我只是尝试循环遍历它:使用for i in range(len(contents)): print content[i],它只是打印出很多数字。

标签: python json byte python-requests decoding


【解决方案1】:

您是否尝试使用json 模块对其进行解析?

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

【讨论】:

  • 是的,我得到了:JSON object must be str, not 'bytes'
  • 你什么时候做json.loads(response.content.decode('latin1'))?
  • 响应对象中应该有一个标头告诉您它具有什么编码。您应该使用该编解码器对内容进行解码,否则任何不寻常的字符(表情符号、重音符号、一些引号字符……)最终都会出现乱码。查看@salah 的答案
  • @mzc 请将content.decode 评论直接添加到答案中。
  • @mzc, decode('latin1') 并不总是有效,如果 content-type 是text/html; charset=UTF-8,它会失败。
【解决方案2】:

另一种解决方案是使用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.

【讨论】:

【解决方案3】:

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

你想要

import json

data = json.loads(r.text)

【讨论】:

  • 我有类似的问题,当我使用 r.text 时,它是空的。
  • 那么可能服务器什么都没有返回。
  • 我正在请求网页的源代码/HTML (dockethound.com),当我使用 r.content 时,它会显示出来。
猜你喜欢
  • 2016-05-09
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2013-12-19
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
相关资源
最近更新 更多