python-3.x - 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 ...}
我应该如何解码这些消息?
解决方案
响应是一组 utf-8 编码的字符串字节,其中可能包含不在 ASCII 表中的字符。如果发生这种情况,您会收到上述错误。所以你可以忽略错误
r.text.encode('ascii', 'ignore')
或将响应处理为 utf-8 字符串
推荐阅读
- google-cloud-platform - 将数据从 API 上传到 GCP 数据准备
- java - 如何将列表直接实例化为实际参数?
- javascript - 传单弹出窗口无法更改位置
- python - 如何将一列字符串转换为超链接?
- node.js - 成功购买后如何阻止 Stripe 覆盖客户端的会话 cookie
- python - 可视代码远程终端上的 Anaconda 命令停止工作
- asynchronous - 在 Trio 中,如何在不等待的情况下将数据写入套接字?
- python - 熊猫跳过单元格值的行
- delphi - 释放 TStringlist 作为函数结果?
- architecture - 需要一些关于微服务之间异步通信的设计指针