gpt4 book ai didi

python - 使用urllib在Python 3.5中获取网页的最终重定向

转载 作者:行者123 更新时间:2023-12-02 04:34:28 25 4
gpt4 key购买 nike

this post中一样,我尝试将网页的最终重定向为:

import urllib.request
response = urllib.request.urlopen(url)
response.geturl()

但这不起作用,因为在尝试使用 urlopen时收到“HTTPError:HTTP错误300:多项选择”错误。

请参阅这些方法的文档 here

编辑:

这个问题与 Python: urllib2.HTTPError: HTTP Error 300: Multiple Choices问题不同,因为它们跳过了导致错误的页面,而我必须获得最终的目标。

最佳答案

如@abccd所建议,我使用了requests库。因此,我将描述解决方案。

import requests

url_base = 'something' # You need this because the redirect URL is relative.
url = url_base + 'somethingelse'

response = requests.get(url)

# Check if the request returned with the 300 error code.
if response.status_code == 300:
redirect_url = url_base + response.headers['Location'] # Get new URL.
response = requests.get(redirect_url) # Make a new request.

关于python - 使用urllib在Python 3.5中获取网页的最终重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44908357/

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