
python requests库在默认情况下会自动跟随http重定向,导致无法直接获取3xx系列状态码。本文将详细解释这一机制,并提供通过设置allow_redirects=false来禁用自动重定向的方法,从而准确捕获原始的重定向状态码,这对于需要分析链接跳转行为的场景至关重要。
在进行网络请求时,我们常常需要获取HTTP响应的状态码来判断请求结果。然而,使用Python的requests库时,有时会发现对于某些已知会发生重定向的URL(例如,返回301或302状态码),我们最终却收到了200 OK的状态码。这通常不是因为URL没有重定向,而是因为requests库的默认行为——自动跟随重定向。
HTTP重定向是一种常见的Web机制,服务器通过返回3xx系列状态码(如301 Moved Permanently、302 Found、307 Temporary Redirect、308 Permanent Redirect)来告知客户端请求的资源已移动到新的URL。客户端(如浏览器或requests库)在收到这些状态码后,会根据响应头中的Location字段自动向新的URL发起请求。
requests库为了方便用户,默认情况下会将allow_redirects参数设置为True。这意味着当你调用requests.get()时,如果服务器返回了重定向状态码,requests会自动发起新的请求去访问重定向后的URL,直到遇到非重定向状态码(如200 OK,404 Not Found等)或达到最大重定向次数限制。最终,response.status_code将是最终目的地的状态码,而原始的3xx状态码则会被“隐藏”。
许多开发者在尝试检测URL状态时会遇到以下困惑:
立即学习“Python免费学习笔记(深入)”;
import requests url_to_check = "http://example.com/old-page" # 假设这个URL会302重定向到 /new-page response = requests.get(url_to_check, timeout=5) print(response.status_code) # 预期302,但可能输出200
上述代码中,如果http://example.com/old-page确实发生了302重定向,requests库会自动跟随到http://example.com/new-page,并返回new-page的响应状态码,通常是200。这就导致我们无法直接获取到原始的302状态码。
要解决这个问题,我们需要显式地告诉requests库不要自动跟随重定向。这可以通过将requests.get()(或其他请求方法,如post、head等)的allow_redirects参数设置为False来实现。
import requests url_to_check = "http://example.com/old-page" # 假设这个URL会302重定向到 /new-page response = requests.get(url_to_check, timeout=5, allow_redirects=False) print(response.status_code) # 现在将准确输出302
通过设置allow_redirects=False,requests库会在收到第一个重定向响应时就停止,并将其作为最终响应返回。此时,response.status_code将准确反映原始的重定向状态码(如301、302等)。
以下是一个结合了CSV文件处理的完整示例,演示如何准确检测URL状态,包括重定向状态码:
import csv
import requests
def check_url_status(url: str) -> str:
"""
检查URL的状态,并返回描述性状态字符串。
通过设置allow_redirects=False来捕获原始的重定向状态码。
"""
try:
# 禁用自动重定向,以便捕获3xx状态码
response = requests.get(url, timeout=5, allow_redirects=False)
status_code = response.status_code
# 如果需要查看重定向历史,可以在这里检查 response.history
# 例如:
# if response.history:
# print(f"URL: {url} - 重定向路径: {[r.url for r in response.history]}")
if 200 <= status_code <= 299:
return f"活动 ({status_code})"
elif status_code == 300:
return f"多重选择重定向 ({status_code})"
elif status_code == 301:
return f"永久移动重定向 ({status_code})"
elif status_code == 302:
return f"临时移动重定向 ({status_code})"
elif 303 <= status_code <= 399: # 涵盖303 See Other, 307 Temporary Redirect, 308 Permanent Redirect
return f"重定向 ({status_code})"
elif 400 <= status_code <= 499:
return f"客户端错误 ({status_code})"
elif 500 <= status_code <= 599:
return f"服务器错误 ({status_code})"
else:
return f"未知状态 ({status_code})"
except requests.exceptions.Timeout:
return "错误: 请求超时"
except requests.exceptions.ConnectionError:
return "错误: 连接失败"
except requests.exceptions.RequestException as e:
return f"错误: {e}"
except Exception as e:
return f"未知错误: {e}"
# 假设 urls.csv 文件存在,并且每行包含一个待检查的URL。
# 示例 urls.csv 内容:
# http://www.google.com
# http://httpbin.org/status/404
# http://httpbin.org/redirect-to?url=http://example.com
# http://www.nonexistent-domain-12345.com
# 读取URL列表
urls_to_check = []
try:
with open("urls.csv", "r", encoding="utf-8") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row: # 确保行不为空
urls_to_check.append(row[0].strip())
except FileNotFoundError:
print("错误: urls.csv 文件未找到。请确保文件存在并包含URL列表。")
exit()
except Exception as e:
print(f"读取urls.csv时发生错误: {e}")
exit()
# 检查每个URL并写入结果
if urls_to_check:
with open("url_status.csv", "w", newline="", encoding="utf-8") as outfile:
writer = csv.writer(outfile)
writer.writerow(["URL", "状态"])
for url in urls_to_check:
status = check_url_status(url)
print(f"检查 {url}: {status}") # 实时输出进度
writer.writerow([url, status])
print("\nURL状态已成功写入 url_status.csv!")
else:
print("未从 urls.csv 中读取到任何URL。")response = requests.get("http://shorturl.com/xyz", allow_redirects=True)
if response.history:
for resp in response.history:
print(f"重定向自: {resp.url}, 状态码: {resp.status_code}")
print(f"最终URL: {response.url}, 最终状态码: {response.status_code}")requests库的allow_redirects参数是控制HTTP重定向行为的关键。通过将其设置为False,我们可以绕过默认的自动重定向机制,从而准确捕获到服务器返回的原始3xx系列状态码。理解并正确使用这个参数,对于需要精确分析网络请求流程和URL跳转行为的场景至关重要。根据具体的应用需求,选择是否禁用自动重定向,将使你的网络请求处理更加灵活和精确。
以上就是深入理解Python requests库的重定向处理与3xx状态码获取的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号