gpt4 book ai didi

python - HTTP 301重定向url编码问题

转载 作者:行者123 更新时间:2023-12-01 09:17:17 38 4
gpt4 key购买 nike

我正在使用 Python 的 requests.get() 来获取一些 Facebook 个人资料 HTML。其中一些将请求重定向到新的 url。当这个新的 url 包含特殊字符(例如 'á')时,request.get() 方法会进入重定向循环,直到引发异常。我找到了一种解决方法来更正重定向 URL 字符串,该字符串位于“Location”键下的响应 header 中,但它远非一个优雅的解决方案。

import requests

# This case works. Response [200]
r = requests.get('https://www.facebook.com/profile.php?id=4')
print(r)

# This fails. Redirect location has special characters.
# raises requests.exceptions.TooManyRedirects: Exceeded 30 redirects.
not_working_url = 'https://www.facebook.com/profile.php?id=100010922979377'
try:
r = requests.get(not_working_url)
except Exception as e:
print(e) # Exceeded 30 redirects.

# Workaround
r = requests.get(not_working_url,
allow_redirects=False)
redirect_url = r.headers["Location"]
print(redirect_url)
# "https://www.facebook.com/people/Tomás-Navarro-Febre/100010922979377"
# Special character 'á' on "/Tomás_Navarro_Febre/" is displayed as 'á'.

# This fixes the string.
redirect_url = redirect_url.encode('raw_unicode_escape').decode('utf-8')
print(redirect_url)
# "https://www.facebook.com/people/Tomás-Navarro-Febre/100010922979377"

# Now it works. Response [200]
r = requests.get(redirect_url)
print(r)

必须有更好的方法来处理这个问题。我尝试了一堆不同的 header ,并使用 requests.Session(),但没有一个起作用。预先感谢您的帮助。

最佳答案

header 通常编码为 Latin-1,因此 requests 使用它来解码所有 header 。然而,在实践中,Location header 通常使用 UTF-8 代替。然后你看到的是Mojibake ,在本例中 UTF-8 数据解码为 Latin-1。

从请求 2.14.0(2017 年 5 月发布)开始,库 specifically decodes the Location header as UTF-8 ,正是为了避免您遇到的问题。升级您的请求库。

如果您无法升级,您可以对 Session 类进行子类化以在本地“修补”问题:

class UTF8RedirectingSession(requests.Session):
def get_redirect_target(self, resp):
if resp.is_redirect:
return resp.headers['location'].encode('latin1').decode('utf8')
return None

然后使用

with UTF8RedirectingSession() as session:
response = session.get(...)

关于python - HTTP 301重定向url编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127307/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com