python发送请求SSL验证设置
这个错误通常是由于SSL/TLS握手失败导致的,可能原因包括证书验证问题、不兼容的加密协议或网络连接中断。以下是几种解决方案,按推荐顺序排列:
方案一:临时禁用SSL验证(快速测试)
response = requests.get(url=url, headers=header, verify=False)
注意:生产环境不推荐长期禁用验证,存在安全风险
方案二:指定TLS版本(推荐)
response = requests.get(url=url,headers=header,ssl_version='TLSv1_2' # 显式指定TLS 1.2版本
)
方案三:添加重试机制
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retrysession = requests.Session()
retry = Retry(total=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('https://', adapter)response = session.get(url=url, headers=header)
方案四:检查本地环境
- 更新证书库:运行
pip install --upgrade certifi
- 检查系统时间:确保系统时间准确
- 防火墙排查:临时禁用防火墙/安全软件测试
方案五:完整改进代码
import os
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retryurl = 'https://www.hainan.gov.cn/.../files/eae7d9e018bf468794e87e690eef3a95.zip'headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36","Accept": "*/*",
}# 创建带重试的Session
session = requests.Session()
retry = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)try:# 添加超时参数response = session.get(url, headers=headers, timeout=10, verify=True)response.raise_for_status()# 确保目录存在os.makedirs('test_file', exist_ok=True)with open('test_file/test2.zip', 'wb') as f:f.write(response.content)except requests.exceptions.RequestException as e:print(f"请求失败: {type(e).__name__}: {e}")
except Exception as e:print(f"其他错误: {e}")
补充建议:
- 先在浏览器测试:手动访问该URL确认是否可下载
- 检查文件路径:确保
test_file
目录存在 - 尝试简单请求:先用
curl
或Postman测试基本连接性 - 更新依赖库:
pip install --upgrade requests urllib3
如果问题持续存在,可能是服务器端配置问题(如仅支持特定TLS版本),建议联系网站管理员确认支持的加密协议。