首页 > 解决方案 > Python 请求 utf-8 后响应得到一个 ascii 解码错误

问题描述

我通过 python 请求将发布请求发送到 RESTful api,有时我在 r.text、r.content 和requests.utils.get_unicode_from_response(r) 操作中收到以下错误。

我正在使用python3。

r 是:

r = requests.post(...)

错误信息是:

'ascii' codec can't encode character '\u015f' in position 133: ordinal not in range(128)

( \ 字符和位置信息在不同的请求中会发生变化,但消息的其余部分是相同的。)

我试图提取发布响应的编码信息,他们都告诉我编码是 utf-8 但我无法解码响应,我不明白为什么 utf-8 编码字节会出现 ascii 错误(而不是UTF-8 错误)。

以下是我试图找出解码方法的方法:

>>> r.encoding
>>> utf-8

>>> chardet.detect(r.content)
>>> {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

>>> r.headers
>>> {... 'Content-Type': 'application/json; charset=utf-8 ...}

我应该如何解码这些消息?

标签: python-3.xencodingutf-8python-requestsdecoding

解决方案


响应是一组 utf-8 编码的字符串字节,其中可能包含不在 ASCII 表中的字符。如果发生这种情况,您会收到上述错误。所以你可以忽略错误

r.text.encode('ascii', 'ignore')

或将响应处理为 utf-8 字符串


推荐阅读