如何使用请求跟踪页面重定向

How to follow page redirects using requests

我有这个简单的代码:

import requests
r = requests.get('https://yahoo.com')
print(r.url)

执行后打印:

https://uk.yahoo.com/?p=us

我想看:

  1. 在到达 https://uk.yahoo.com/?p=us 之前发生了多少次重定向(显然,我最初输入 https://yahoo.com 时有重定向)?

  2. 我也想保存每一页的内容,不仅仅是最后一页。如何做到这一点?

使用response.history。从 documentation...

The Response.history list contains the Response objects that were created in order to complete the request. The list is sorted from the oldest to the most recent response.

因此,要获取中间 URL 的数量,您可以这样做:

response = requests.get(url)
print(len(response.history))

要获取这些 URL 的实际内容以及它们的响应包含的内容,您可以执行以下操作:

for resp in response.history:
    print(resp.url, resp.text)

如果需要,您还可以向中间 URL 提交新请求,并将可选参数 allow_redirects 设置为 False:

r = requests.get(resp.url, allow_redirects=False)