Python requests代理(Proxy)使用教程
在Python中使用requests
库设置代理(Proxy)非常简单,以下是详细步骤和常见场景说明:
一、基础代理设置
import requestsproxies = {"http": "http://10.10.1.10:3128", # HTTP代理"https": "http://10.10.1.10:1080" # HTTPS代理(注意协议头可能不同)
}response = requests.get("https://example.com", proxies=proxies)
print(response.text)
二、全局代理设置(所有请求自动使用)
# 通过环境变量设置(推荐)
import os
os.environ["HTTP_PROXY"] = "http://10.10.1.10:3128"
os.environ["HTTPS_PROXY"] = "http://10.10.1.10:1080"# 之后所有requests请求自动使用代理
response = requests.get("https://example.com")
三、需要认证的代理
如果代理需要用户名和密码:
proxies = {"http": "http://username:password@10.10.1.10:3128","https": "http://username:password@10.10.1.10:1080"
}response = requests.get("https://example.com", proxies=proxies)
四、使用SOCKS代理
需先安装依赖:
pip install requests[socks]
代码示例:
proxies = {"http": "socks5://127.0.0.1:1080", # SOCKS5代理"https": "socks5://127.0.0.1:1080"
}response = requests.get("https://example.com", proxies=proxies)
五、异常处理
添加代理可能失败时的处理:
try:response = requests.get("https://example.com", proxies=proxies, timeout=5)response.raise_for_status()
except requests.exceptions.ProxyError as e:print(f"代理连接失败: {e}")
except requests.exceptions.RequestException as e:print(f"请求异常: {e}")
六、最佳实践建议
-
使用Session对象:保持代理设置一致性
session = requests.Session() session.proxies.update(proxies) response = session.get("https://example.com")
-
代理池管理:对爬虫项目建议使用代理池轮换
proxies_list = ["http://proxy1:port","http://proxy2:port" ] # 随机选择一个代理 proxy = random.choice(proxies_list)
-
安全提示:
- 避免在代码中硬编码敏感信息(如密码)
- 使用环境变量或配置文件存储代理凭证
- 遵守目标网站的
robots.txt
规则
常见问题排查
- 代理无效:检查代理地址、端口、协议是否匹配
- 连接超时:尝试更换代理或调整
timeout
参数 - SSL错误:添加
verify=False
(临时方案,不推荐长期使用)response = requests.get("https://example.com", proxies=proxies, verify=False)
如果需要更高级的配置(如自定义适配器),可参考requests官方文档。