
Python requests设置代理的基本方法
使用Python的requests库设置代理非常简单,只需要在请求中添加proxies参数即可。代理IP能帮助我们在网络请求时隐藏真实IP地址,提高请求成功率。
import requests
设置代理
proxies = {
'http': 'http://username:password@proxy.ipipgo.com:8080',
'https': 'https://username:password@proxy.ipipgo.com:8080'
}
发送带代理的请求
response = requests.get('http://httpbin.org/ip', proxies=proxies)
print(response.json())
上面的代码展示了最基本的代理设置方式。其中username和password需要替换为ipipgo提供的认证信息,proxy.ipipgo.com:8080需要替换为实际的代理服务器地址和端口。
不同类型的代理协议设置
根据代理服务器的支持情况,我们可以设置不同的代理协议。ipipgo支持HTTP、HTTPS和SOCKS5协议,满足各种业务场景需求。
HTTP代理设置
proxies_http = {
'http': 'http://user:pass@proxy.ipipgo.com:8080',
'https': 'http://user:pass@proxy.ipipgo.com:8080'
}
HTTPS代理设置
proxies_https = {
'http': 'https://user:pass@proxy.ipipgo.com:443',
'https': 'https://user:pass@proxy.ipipgo.com:443'
}
SOCKS5代理设置
proxies_socks5 = {
'http': 'socks5://user:pass@proxy.ipipgo.com:1080',
'https': 'socks5://user:pass@proxy.ipipgo.com:1080'
}
会话级别的代理设置
如果需要多个请求使用相同的代理配置,可以使用Session对象来管理会话,这样就不需要在每个请求中都设置代理。
import requests
创建会话对象
session = requests.Session()
设置会话级别的代理
session.proxies = {
'http': 'http://user:pass@proxy.ipipgo.com:8080',
'https': 'http://user:pass@proxy.ipipgo.com:8080'
}
后续所有请求都会自动使用代理
response1 = session.get('http://httpbin.org/ip')
response2 = session.get('http://httpbin.org/user-agent')
动态轮换代理IP的实现
在实际应用中,为了避免被目标网站封禁,我们需要定期更换代理IP。ipipgo的动态住宅代理支持自动轮换IP,确保业务稳定运行。
import requests
import time
class ProxyRotator:
def __init__(self, proxy_list):
self.proxy_list = proxy_list
self.current_index = 0
def get_next_proxy(self):
proxy = self.proxy_list[self.current_index]
self.current_index = (self.current_index + 1) % len(self.proxy_list)
return proxy
代理IP列表(实际使用时应从ipipgo API获取)
proxies = [
'http://user:pass@proxy1.ipipgo.com:8080',
'http://user:pass@proxy2.ipipgo.com:8080',
'http://user:pass@proxy3.ipipgo.com:8080'
]
rotator = ProxyRotator(proxies)
for i in range(10):
current_proxy = rotator.get_next_proxy()
proxies_config = {'http': current_proxy, 'https': current_proxy}
try:
response = requests.get('http://httpbin.org/ip', proxies=proxies_config, timeout=10)
print(f"请求{i+1}成功,使用IP:{response.json()}")
except Exception as e:
print(f"请求{i+1}失败:{e}")
time.sleep(1) 控制请求频率
代理IP的异常处理
在使用代理IP时,可能会遇到连接超时、认证失败等问题,合理的异常处理能保证程序的稳定性。
import requests
from requests.exceptions import ProxyError, ConnectTimeout, ConnectionError
def safe_request_with_proxy(url, proxies, retries=3):
for attempt in range(retries):
try:
response = requests.get(url, proxies=proxies, timeout=10)
return response
except ProxyError as e:
print(f"代理错误(尝试{attempt+1}):{e}")
except ConnectTimeout as e:
print(f"连接超时(尝试{attempt+1}):{e}")
except ConnectionError as e:
print(f"连接错误(尝试{attempt+1}):{e}")
if attempt < retries - 1:
print("等待5秒后重试...")
time.sleep(5)
return None
使用示例
proxies = {
'http': 'http://user:pass@proxy.ipipgo.com:8080',
'https': 'http://user:pass@proxy.ipipgo.com:8080'
}
response = safe_request_with_proxy('http://httpbin.org/ip', proxies)
if response:
print("请求成功:", response.json())
else:
print("所有重试均失败")
ipipgo代理服务推荐
ipipgo提供高质量的代理IP服务,特别适合Python开发者使用。其动态住宅代理IP资源丰富,覆盖全球220多个国家和地区。
ipipgo的主要优势:
- 动态住宅代理IP资源总量高达9000万+
- 支持HTTP(S)和SOCKS5全协议
- 按流量计费,灵活应对不同业务需求
- 支持轮换和粘性会话两种模式
- 可指定国家、城市级别的精确定位
对于需要稳定IP的业务场景,ipipgo还提供静态住宅代理服务,确保业务长期稳定运行。
常见问题解答
Q: 代理IP连接超时怎么办?
A: 首先检查网络连接是否正常,然后确认代理地址和端口是否正确。如果使用ipipgo服务,可以尝试更换其他代理服务器节点。
Q: 如何测试代理IP是否生效?
A: 可以通过访问http://httpbin.org/ip来验证代理是否生效,该接口会返回当前请求使用的IP地址。
Q: 代理IP的认证失败是什么原因?
A: 认证失败通常是由于用户名或密码错误导致的。请确认ipipgo提供的认证信息是否正确,特别是特殊字符是否需要转义。
Q: 如何选择合适的代理类型?
A: 根据业务需求选择:需要频繁更换IP的选择动态住宅代理,需要稳定IP的选择静态住宅代理。ipipgo提供多种套餐满足不同需求。
Q: 代理IP速度慢如何优化?
A: 可以尝试选择距离目标网站较近的代理服务器,或者联系ipipgo技术支持优化路由。适当调整超时时间也能改善使用体验。

