要解决不同浏览器在响应头中有不同的重定向位置,并返回HTTP 502错误的问题,可以使用以下代码示例:
import requests
url = "https://example.com" # 要重定向的URL
try:
response = requests.get(url, allow_redirects=False)
if response.status_code == 302:
redirect_url = response.headers.get("Location") # 获取重定向位置
response = requests.get(redirect_url)
elif response.status_code == 502:
redirect_url = response.headers.get("Refresh") # 获取重定向位置
if redirect_url.startswith("0;url="):
redirect_url = redirect_url[7:] # 去除前缀
response = requests.get(redirect_url)
print(response.text) # 打印重定向后的页面内容
except requests.exceptions.RequestException as e:
print("Error:", e)
上述代码使用了Python的requests库来发送HTTP请求。在请求时,使用allow_redirects=False
来禁止自动重定向。
如果返回的状态码是302,则获取响应头中的Location
字段,并使用新的URL进行请求。
如果返回的状态码是502,则获取响应头中的Refresh
字段。如果字段以0;url=
开头,则去除前缀,并使用新的URL进行请求。
最后,打印重定向后的页面内容。
请注意,上述代码仅提供了一种解决方案,并不能保证适用于所有情况。根据具体的重定向方式和浏览器行为的不同,可能需要进行相应的调整。