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

use*_*654 -1 python web-scraping python-3.x python-requests python-requests-html

我有这个简单的代码:

import requests
r = requests.get('https://yahoo.com')
print(r.url)
Run Code Online (Sandbox Code Playgroud)

执行后打印:

https://uk.yahoo.com/?p=us
Run Code Online (Sandbox Code Playgroud)

我想看看:

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

  2. 我还想保存每一页的内容,而不仅仅是最后一页。这个怎么做?

And*_*bie 6

使用response.history。从文档中...

Response.history 列表包含为完成请求而创建的 Response 对象。该列表按从最旧到最新的响应排序。

因此,要获取中间 URL 的数量,您可以执行以下操作:

response = requests.get(url)
print(len(response.history))
Run Code Online (Sandbox Code Playgroud)

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

for resp in response.history:
    print(resp.url, resp.text)
Run Code Online (Sandbox Code Playgroud)

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

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