Python 3.x 请求使用 unicode 字符进行重定向

标签 python python-3.x unicode character-encoding python-requests

我尝试在 Python 3.x 中使用 requests.get() 获取以下 URL: http://www.finanzen.net/suchergebnis.asp?strSuchString=DE0005933931 (此 URL 由基本 URL 和搜索字符串 DE0005933931 组成)。

请求被重定向(通过 HTTP 状态代码 301)到 http://www.finanzen.net/etf/ishares_core_dax%AE_ucits_etf_de在浏览器中(URL 中包含 character 0xAE 字符®)。将 requests.get() 与重定向 URL 一起使用也可以。

当尝试使用Python 2.7获取搜索字符串URL时,一切正常,并且我得到了重定向的响应,使用Python 3.x我收到以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 21: invalid start byte

用于测试的代码片段:

import requests

url_1 = 'http://www.finanzen.net/suchergebnis.asp?strSuchString=LU0274208692'
# redirected to http://www.finanzen.net/etf/db_x-trackers_msci_world_index_ucits_etf_1c
url_2 = 'http://www.finanzen.net/suchergebnis.asp?strSuchString=DE0005933931'
# redirected to http://www.finanzen.net/etf/ishares_core_dax%AE_ucits_etf_de

print(requests.get(url_1).status_code)  # working
print(requests.get(url_2).status_code)  # error with Python 3.x

更多信息:

  • 我正在 Windows 7 上使用 Python 3.6.3 和 requests.__version__ = '2.18.4' 但我 其他 Python 版本(3.4、3.5)也会出现相同的错误。
  • 使用其他搜索字符串,一切都适用于 Python 3.x, 例如 http://www.finanzen.net/suchergebnis.asp?strSuchString=LU0274208692
  • 有趣的是,我什至收到了内部服务器错误,并显示 https://www.hurl.it尝试获取上述 URL。也许这不是Python的问题。

知道为什么这在 Python 2.7 中有效但在 Python 3.x 中无效以及我能对此做什么?

最佳答案

服务器使用编码为 Latin-1 的 URL 进行响应,该 URL 未进行 URL 编码;非 ASCII 字节显示为 0x?? 十六进制转义:

Location: /etf/ishares_core_dax0xAE_ucits_etf_de

0xAE字节不是有效的URL字符;服务器在这里违反了标准。他们应该发送的是

Location: /etf/ishares_core_dax%AE_ucits_etf_de

Location: /etf/ishares_core_dax%C2%AE_ucits_etf_de

对 URL 的 Latin-1 或 UTF-8 编码使用转义数据。

我们可以通过不更改地返回 Location header 来修补请求,使其在面对此错误时更加稳健:

from requests.sessions import SessionRedirectMixin

def get_redirect_target(
        self, resp, _orig=SessionRedirectMixin.get_redirect_target):
    try:
        return _orig(self, resp)
    except UnicodeDecodeError:
        return resp.headers['location']

SessionRedirectMixin.get_redirect_target = get_redirect_target

应用此补丁后,重定向将按预期工作。

created a pull request改进位置处理。

关于Python 3.x 请求使用 unicode 字符进行重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113376/

相关文章:

python - 错误 : gunicorn: Failed to find application object 'app' in 'app'

python - 关于如何根据当前 df 列创建新列的问题

python - Pandas - 如何根据条件创建新列

Python:从时间戳中添加或删除时区小时并获取实际时间

python - 在 Python 2 和 3 中导入包内和包外都有效的结构?

python - 我是 Python 新手,在向程序添加一行代码后设法使 IDLE 崩溃

Python 3 unicode 编解码器错误在 tkinter 中绑定(bind)鼠标滚轮

python - Pandas 造型 : Conditionally change background color of column by absolute value

java - 查找非英文字符的 unicode

java - 如何在Java中删除字符串中Unicode杂项符号的Unicode十进制值