Requests - 处理重定向
Requests - 处理重定向
Section titled “Requests - 处理重定向”本章探讨 Requests 库如何处理 URL 重定向。默认情况下,Requests 会自动跟随 GET、OPTIONS、POST、PUT、PATCH、DELETE 和 HEAD 请求的重定向。
自动重定向和历史记录
Section titled “自动重定向和历史记录”当服务器响应重定向状态码(如 301 Moved Permanently 或 302 Found)时,Requests 会自动向 Location 头中指定的 URL 发起新的请求。Response 对象的 history 属性存储了一个 Response 对象列表,这些对象是该重定向链的一部分,按从最旧到最新的顺序排列。
示例:跟随重定向
Section titled “示例:跟随重定向”import requests
# httpbin.org/redirect/N will redirect N timesurl = 'http://httpbin.org/redirect/2'response = requests.get(url)
print(f"Final URL: {response.url}")print(f"Status Code: {response.status_code}")print(f"History: {response.history}")
if response.history: print("Redirection path:") for resp_in_history in response.history: print(f" - Status: {resp_in_history.status_code}, URL: {resp_in_history.url}")Final URL: http://httpbin.org/getStatus Code: 200History: [<Response [302]>, <Response [302]>]Redirection path: - Status: 302, URL: http://httpbin.org/redirect/2 - Status: 302, URL: http://httpbin.org/relative-redirect/1response.history 列表包含 Response 对象。在此示例中,发生了两次重定向(都是 302 Found 状态码)。最终 URL 是 http://httpbin.org/get,状态码为 200。
你可以通过在请求中将 allow_redirects 参数设置为 False 来阻止 Requests 自动跟随重定向。这适用于所有 HTTP 方法。
示例:禁用重定向
Section titled “示例:禁用重定向”import requests
url = 'http://httpbin.org/redirect/1'response = requests.get(url, allow_redirects=False)
print(f"Status Code: {response.status_code}")print(f"History (should be empty): {response.history}")print(f"Location header: {response.headers.get('Location')}")# The content of a 3xx response often contains information about the redirect# print(f"Response Text:\n{response.text[:200]}...") # Show first 200 charsStatus Code: 302History (should be empty): []Location header: /relative-redirect/0当 allow_redirects 为 False 时,请求会在第一个重定向响应处停止。状态码是 302(或另一个重定向码),response.history 为空,并且你可以检查 response.headers['Location'] 来查看它原本会重定向到哪里。