在Python网络编程中,通过HTTP代理发送请求是常见的需求,无论是为了访问受限资源、保护隐私还是实现爬虫功能。本文将详细介绍如何使用Python标准库和第三方库通过HTTP代理发送请求。
使用urllib库通过代理发送请求****
Python标准库中的urllib提供了基本的HTTP请求功能,可以通过ProxyHandler配置代理:
python
from urllib.request import ProxyHandler, build_opener, Request, urlopen | |
---|---|
import urllib.parse | |
# 配置代理 | |
proxy = ProxyHandler({ | |
'http': 'http://123.123.123.123:8080', | |
'https': 'http://123.123.123.123:8080' | |
}) | |
# 创建自定义opener | |
opener = build_opener(proxy) | |
# 发送请求 | |
url = 'example.com' | |
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) | |
response = opener.open(req) | |
# 读取响应 | |
print(response.read().decode('utf-8')) |
使用requests库通过代理发送请求(推荐)****
requests库提供了更简洁的API,是Python中最流行的HTTP客户端:
python
import requests | |
---|---|
# 基础代理配置 | |
proxies = { | |
'http': 'http://123.123.123.123:8080', | |
'https': 'http://123.123.123.123:8080' | |
} | |
# 发送GET请求 | |
response = requests.get('example.com', proxies=proxies) | |
print(response.text) | |
# 发送POST请求 | |
data = {'key': 'value'} | |
response = requests.post('example.com/api', proxies=proxies, data=data) |
带认证的代理请求****
如果代理服务器需要用户名和密码认证:
python
# 方法1:URL中包含认证信息 | |
---|---|
proxies = { | |
'http': 'http://username:password@123.123.123.123:8080' | |
} | |
# 方法2:使用HTTPProxyAuth(更安全) | |
from requests.auth import HTTPProxyAuth | |
auth = HTTPProxyAuth('username', 'password') | |
response = requests.get('example.com', proxies=proxies, auth=auth) |
SOCKS代理支持****
requests本身不支持SOCKS代理,但可以通过安装requests[socks]实现:
python
# 安装:pip install requests[socks] | |
---|---|
proxies = { | |
'http': 'socks5://user:pass@host:port', | |
'https': 'socks5://user:pass@host:port' | |
} | |
response = requests.get('example.com', proxies=proxies) |
代理池实现****
对于需要轮换代理的场景:
python
import random | |
---|---|
import requests | |
proxy_pool = [ | |
'http://proxy1:8080', | |
'http://proxy2:8080', | |
'http://proxy3:8080' | |
] | |
def get_with_proxy(url): | |
proxies = { | |
'http': random.choice(proxy_pool), | |
'https': random.choice(proxy_pool) | |
} | |
try: | |
return requests.get(url, proxies=proxies, timeout=5) | |
except: | |
return get_with_proxy(url) # 失败重试 | |
response = get_with_proxy('example.com') | |
print(response.text) |
注意事项****
1. 代理稳定性:免费代理通常不可靠,建议使用付费代理服务
2. 异常处理:网络请求可能失败,应添加适当的异常处理
3. 请求头设置:有些网站会检查User-Agent等请求头
4. 超时设置:避免因代理问题导致程序挂起
5. 隐私保护:谨慎使用不可信的代理服务
通过以上方法,你可以灵活地在Python中通过HTTP代理发送各种HTTP请求,满足不同的网络访问需求。