【问题标题】:Fixing double-encoded utf-8 returned by Requests修复 Requests 返回的双编码 utf-8
【发布时间】:2014-03-06 22:16:52
【问题描述】:

我正在使用 Requests 检索 Atom 响应,但遇到了编码问题:

当我使用 curl 检索它时,它是正确的,显示 Ä:

<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api">
<title>The power broker : Robert Moses and the fall of New York</title>
(snip)
<content zapi:type="citation" type="xhtml">
    <span xmlns="http://www.w3.org/1999/xhtml">(Robert Ä. Caro 1974)</span>
</content>
</entry>

但是当我在 Python 2.7.4 上使用 requests 2.2.1 检索它时,我得到了这个 unicode 响应:

import requests
r = requests.get(url)
r.text
u'<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api">
<title>The power broker : Robert Moses and the fall of New York</title>
(snip)
<content zapi:type="citation" type="xhtml">
    <span xmlns="http://www.w3.org/1999/xhtml">(Robert \u0102\x84. Caro 1974)</span>
</content>
</entry>'

当然,将其编码为 utf-8 并不会返回我的 Ä。做什么?

【问题讨论】:

  • 您可以添加您的requests 代码吗?
  • @Drewnes 哎呀,对不起。完成。
  • 改用r.content

标签: python unicode encoding utf-8 python-requests


【解决方案1】:

由于您没有包含服务器发送的任何响应标头,因此我无法真正得出结论,但我猜是服务器发回了带有错误字符集的标头的 utf8 编码字符串:

Content-Type: text/html; charset=iso-8859-1

因此,该请求会将其视为字节流(或 python2 中的 str),并根据该字符集将该字符串解码为 un​​icode 字符串。将 unicode 重新编码为 latin1 并解码回 utf8 应该会得到原始字符串。

r.encode('iso-8859-1').decode('utf8')

但是,是的,使用 r.content 并返回 str 类型,您可以通过将其解码为 utf8 来手动应用正确的编码。

【讨论】:

    【解决方案2】:

    您确定不是 curl 试图创建一个“已知”字母来替换 \u0102 所使用的“Ă”吗?谷歌搜索这个作者的名字,“A”应该是简单的(罗伯特艾伦卡罗)。 u"\x84" 字符本身是一个结束引号 unicode 字符 - (检查 http://www.fileformat.info/info/unicode/category/Cc/list.htm) - 所以这可能是从 somwhere 扫描“Robert "A." Caro" 的 OCR 工件 - 就像你一样在服务器中表示在 Python 端看到它。

    尝试使用带有--raw 选项的curl 来检查这种情况下的实际内容。

    (我玩过弦乐,这个 hipoteses 看起来更有可能 在这种情况下,我比双重编码)。

    【讨论】:

    • 不,我用 Ä 创建了记录,所以它会像这样返回以用于测试目的。罗伯特·卡罗实际上是罗伯特·A·卡罗——很抱歉造成混乱。
    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2012-07-11
    • 2016-11-08
    • 2022-07-26
    相关资源
    最近更新 更多