我尝试在 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/