Python处理HTTP重定向:控制301/302跳转行为

75 阅读1分钟

微信图片_20230808094553.png在Python中,HTTP客户端默认会自动处理301/302重定向,但有时我们需要手动控制这一行为。本文将介绍如何使用requests和http.client等库来精确控制重定向行为。

一、requests库中的重定向控制****

1. 禁止所有重定向****

python

 import requests
  
 response = requests.get('example.com', allow_redirects=False)
 print(response.status_code) # 可能输出301/302而非200

2. 获取重定向历史****

python

 response = requests.get('example.com', allow_redirects=True)
 print(response.history) # 显示所有重定向响应对象列表

3. 自定义重定向限制****

python

 from requests.adapters import HTTPAdapter
  
 class NoRedirectAdapter(HTTPAdapter):
 def send(self, request, **kwargs):
 kwargs['allow_redirects'] = False
 return super().send(request, **kwargs)
  
 session = requests.Session()
 session.mount('http://', NoRedirectAdapter())
 session.mount('https://', NoRedirectAdapter())
  
 response = session.get('example.com')

通过精确控制重定向行为,可以构建更安全、高效的HTTP客户端,特别适合爬虫、API测试和需要严格流量控制的场景。