在python3.5中使用urllib获取网页的最终重定向

2024-03-29 08:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但是当我在尝试使用urlopen时,我得到了“HTTPError:HTTPError 300:multiplechoices”错误,所以这不起作用。在

请参见这些方法的文档here。在

编辑:

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


Tags: 方法importurl网页responserequest错误urllib
1条回答
网友
1楼 · 发布于 2024-03-29 08:19:21

根据@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.

相关问题 更多 >