Python 请求库重定向新 url [英] Python Requests library redirect new url

查看:37
本文介绍了Python 请求库重定向新 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览 Python Requests 文档,但我看不到我想要实现的任何功能.

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

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

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

最终网址是 www.google.co.uk/redirected

如何获取该网址?

解决方案

您正在寻找 请求历史.

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

response = requests.get(someurl)如果响应.历史:print("请求被重定向")对于响应中的响应.history:打印(resp.status_code,resp.url)打印(最终目的地:")打印(response.status_code,response.url)别的:print("请求没有被重定向")

演示:

<预><代码>>>>进口请求>>>response = requests.get('http://httpbin.org/redirect/3')>>>响应.历史(<响应[302]>、<响应[302]>、<响应[302]>)>>>对于响应中的响应.history:...打印(resp.status_code,resp.url)...302 http://httpbin.org/redirect/3302 http://httpbin.org/redirect/2302 http://httpbin.org/redirect/1>>>打印(response.status_code,response.url)200 http://httpbin.org/get

I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve.

In my script I am setting allow_redirects=True.

I would like to know if the page has been redirected to something else, what is the new URL.

For example, if the start URL was: www.google.com/redirect

And the final URL is www.google.co.uk/redirected

How do I get that URL?

解决方案

You are looking for the request history.

The response.history attribute is a list of responses that led to the final URL, which can be found in 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")

Demo:

>>> 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

这篇关于Python 请求库重定向新 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆