我有这个简单的代码:
import requests
r = requests.get('https://yahoo.com')
print(r.url)
执行后,打印:
https://uk.yahoo.com/?p=us
我想看看:
在到达之前发生了多少重定向https://uk.yahoo.com/?p=us
(显然,我https://yahoo.com
最初输入的是重定向)?
我还想保存每一页的内容,而不仅仅是最后一页。这该怎么做?
使用response.history
. 从文档...
Response.history 列表包含为完成请求而创建的 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句