Skip to content

Requests - 处理历史记录

Requests 库中的 response.history 属性为 HTTP 请求的重定向过程提供了有价值的洞察。它记录了重定向链中的每个步骤。

当一个请求导致一个或多个重定向时,response.history 将是一个 Response 对象列表。该列表中的每个对象代表一个发生在收到最终响应之前的请求-响应循环。列表按从最旧的重定向到最新的重定向排序,就在最终响应之前。

如果没有发生重定向,response.history 将是一个空列表 []。

让我们使用一个我们知道会多次重定向的 URL 来检查它的历史记录。

import requests
# This URL will redirect 3 times before landing on /get
url = 'http://httpbin.org/redirect/3'
response = requests.get(url)
print(f"Final URL: {response.url}")
print(f"Final Status Code: {response.status_code}")
print("\nRedirection History:")
if response.history:
for i, resp_in_history in enumerate(response.history):
print(f" Step {i+1}:")
print(f" Status Code: {resp_in_history.status_code}")
print(f" URL: {resp_in_history.url}")
print(f" Redirected from: {resp_in_history.headers.get('Location', 'N/A') if resp_in_history.is_redirect else 'N/A (not a redirect response)'}")
else:
print("No redirections occurred.")
print(f"\nRaw history list: {response.history}")
Final URL: http://httpbin.org/get
Final Status Code: 200
Redirection History:
Step 1:
Status Code: 302
URL: http://httpbin.org/redirect/3
Redirected from: /relative-redirect/2
Step 2:
Status Code: 302
URL: http://httpbin.org/relative-redirect/2
Redirected from: /relative-redirect/1
Step 3:
Status Code: 302
URL: http://httpbin.org/relative-redirect/1
Redirected from: /get
Raw history list: [<Response [302]>, <Response [302]>, <Response [302]>]

通过迭代 response.history,你可以跟踪整个重定向路径,包括状态码和中间 URL。这对于调试重定向问题或理解特定 URL 如何解析特别有用。

response.history 中的每个元素都是一个完整的 Response 对象,这意味着你可以像访问最终的 response 对象一样访问它的头部、内容(尽管对于重定向通常是空的)等。