在Python中,通过设置HTTP或SOCKS代理发送请求,可以实现访问受限资源、隐藏真实IP地址等需求。以下是使用requests库结合requests[socks]扩展或直接使用requests设置HTTP代理的方法。
安装依赖****
如果需要使用SOCKS代理,首先需安装requests[socks]扩展,它基于PySocks库实现SOCKS代理支持。可以通过pip安装:
bash复制代码
| pip install requests[socks] |
|---|
HTTP代理设置****
使用requests库发送HTTP请求并设置HTTP代理非常简单。只需在请求方法中通过proxies参数指定代理地址:
python复制代码
| import requests | |
|---|---|
| proxies = { | |
| 'http': 'http://your_http_proxy:port', | |
| 'https': 'http://your_http_proxy:port' # HTTPS请求通常也使用HTTP代理配置 | |
| } | |
| try: | |
| response = requests.get('example.com', proxies=proxies) | |
| print(response.text) | |
| except requests.exceptions.RequestException as e: | |
| print(f"请求失败: {e}") |
SOCKS代理设置****
对于SOCKS代理,requests[socks]扩展提供了支持。设置方式与HTTP代理类似,只需在proxies字典中指定socks5或socks4协议:
python复制代码
| import requests | |
|---|---|
| proxies = { | |
| 'http': 'socks5://your_socks5_proxy:port', | |
| 'https': 'socks5://your_socks5_proxy:port' # 同样适用于HTTPS | |
| } | |
| try: | |
| response = requests.get('example.com', proxies=proxies) | |
| print(response.text) | |
| except requests.exceptions.RequestException as e: | |
| print(f"请求失败: {e}") |
注意事项****
1. 代理验证:如果代理需要身份验证,可以在代理URL中包含用户名和密码,如http://user:pass@your_http_proxy:port。
2. 错误处理:使用try-except块捕获请求异常,确保程序健壮性。
3. 代理稳定性:选择可靠的代理服务,避免因代理问题导致请求失败。
通过上述方法,可以在Python中轻松设置HTTP或SOCKS代理,实现灵活的网络请求。