我试图在Python3.x中使用requests.get()
获取以下URL:http://www.finanzen.net/suchergebnis.asp?strSuchString=DE0005933931 (这个URL由一个包含搜索字符串DE0005933931
的基本URL组成)。
请求在浏览器中被重定向(通过HTTP状态代码301)到de (在URL中包含字符0xAE字符)。将requests.get()
与重定向URL一起使用也是有效的。
当尝试使用Python2.7获得搜索字符串URL时,所有操作都正常,我得到重定向响应,使用Python3.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
更多信息:
requests.__version__ = '2.18.4'
一起运行Windows7,但在其他Python版本(3.4、3.5)中也出现了同样的错误。Internal Server Error
与https://www.hurl.it试图获得上述网址。也许这不是Python的问题。知道吗,为什么这在Python2.7中有效,而在Python3.x中却不行,我能做些什么呢?
发布于 2017-11-04 17:30:09
服务器响应以拉丁-1编码的URL响应,这是而不是URL编码的;非0x??
十六进制字节显示为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的拉丁-1或UTF-8编码使用转义数据。
我们可以修补requests
,使其在遇到此错误时更加健壮,方法是不改变地返回Location
头:
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
应用此修补程序后,重定向工作将按预期进行。
I 创建了一个拉请求来改进位置处理。
https://stackoverflow.com/questions/47113376
复制相似问题