【问题标题】:Python Requests library redirect new urlPython Requests 库重定向新的 url
【发布时间】:2013-12-26 20:28:43
【问题描述】:

我一直在查看 Python 请求文档,但我看不到任何我想要实现的功能。

在我的脚本中,我设置了allow_redirects=True

我想知道页面是否被重定向到其他地方,新的 URL 是什么。

例如,如果起始 URL 是:www.google.com/redirect

最后的网址是www.google.co.uk/redirected

我如何获得该网址?

【问题讨论】:

标签: python http redirect python-requests


【解决方案1】:

我认为在处理 url 重定向时调用 requests.head 而不是 requests.get 会更安全。检查 GitHub 问题here

r = requests.head(url, allow_redirects=True)
print(r.url)

【讨论】:

  • 这应该是公认的答案。简短而甜蜜。
  • @Volatil3:并非所有服务器都以与 GET 相同的方式响应 HEAD 请求。
【解决方案2】:

您正在寻找request history

response.history 属性是指向最终 URL 的响应列表,可以在 response.url 中找到。

response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

演示:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

【讨论】:

  • httpbin.org 出于某种原因给出了 404,但 httpbingo.org(相同的 URL 方案)对我来说工作得很好。
  • @PrestonBadeer:这是一个已知问题:github.com/postmanlabs/httpbin/issues/617。幸运的是,演示是否适用于答案并不重要。
【解决方案3】:

文档有这个简介https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history

import requests

r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for 

【讨论】:

    【解决方案4】:

    对于python3.5,可以使用如下代码:

    import urllib.request
    res = urllib.request.urlopen(starturl)
    finalurl = res.geturl()
    print(finalurl)
    

    【讨论】:

    • 这是 Python 3.5 的正确答案,我花了一段时间才找到,谢谢
    • 如果您知道如何使用 python3 进行重定向,您能否完成您的回答?谢谢。
    【解决方案5】:

    这回答了一个略有不同的问题,但由于我自己被困在这个问题上,我希望它对其他人有用。

    如果您想使用allow_redirects=False 并直接获取第一个重定向对象,而不是跟随它们的链,并且您只想直接从 302 响应对象中获取重定向位置,那么r.url 赢了不行。相反,它是“位置”标题:

    r = requests.get('http://github.com/', allow_redirects=False)
    r.status_code  # 302
    r.url  # http://github.com, not https.
    r.headers['Location']  # https://github.com/ -- the redirect destination
    

    【讨论】:

    • 谢谢 - 这将我的 URL 推荐脚本(有数千个 url)提高了几秒钟。
    • 你知道r.next 是怎么回事吗?我认为这将包含一个指向重定向 URL 的 PreparedRequest,但似乎并非如此......
    • 值得补充的是,这个答案只会给你第一个重定向 URL。如果此网址在访问时通常会再次重定向到新网址,您将错过它。
    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2011-08-06
    • 2020-09-22
    • 2017-10-10
    • 2017-02-02
    相关资源
    最近更新 更多