【问题标题】:Using urllib to get the final redirect of a webpage in Python 3.5在 Python 3.5 中使用 urllib 获取网页的最终重定向
【发布时间】:2017-12-08 01:37:09
【问题描述】:

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

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

但这不起作用,因为我在尝试使用 urlopen 时收到“HTTPError: HTTP Error 300: Multiple Choices”错误。

请参阅这些方法的文档here

编辑:

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

【问题讨论】:

标签: python python-3.x python-requests python-3.5 urllib


【解决方案1】:

按照@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.

【讨论】:

    猜你喜欢
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多