
Python requests库代理设置基础
当你使用Python的requests库发送网络请求时,有时候会遇到IP被限制的情况。这时候代理IP就能帮上大忙。requests库设置代理非常简单,只需要在请求中添加一个proxies参数即可。
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.text)
上面的代码展示了最基本的代理设置方式。其中username和password需要替换为你实际的认证信息,proxy.ipipgo.com:8080需要替换为代理服务器地址。
不同类型的代理协议设置
根据代理服务器的类型,设置方式会有所不同。主要分为HTTP代理和SOCKS5代理两种:
HTTP代理设置:
proxies = {
'http': 'http://user:pass@proxy.ipipgo.com:8080',
'https': 'https://user:pass@proxy.ipipgo.com:8080'
}
SOCKS5代理设置:
proxies = {
'http': 'socks5://user:pass@proxy.ipipgo.com:1080',
'https': 'socks5://user:pass@proxy.ipipgo.com:1080'
}
需要注意的是,使用SOCKS5代理时需要先安装requests[socks]包:pip install requests[socks]
会话级别的代理设置
如果你需要在一个会话中持续使用同一个代理,可以使用Session对象:
import requests
session = requests.Session()
session.proxies = {
'http': 'http://user:pass@proxy.ipipgo.com:8080',
'https': 'https://user:pass@proxy.ipipgo.com:8080'
}
后续所有使用这个session的请求都会自动使用代理
response1 = session.get('http://httpbin.org/ip')
response2 = session.get('http://httpbin.org/headers')
这种方式特别适合需要保持会话状态或者使用相同代理进行多个请求的场景。
动态代理IP的轮换策略
在实际应用中,经常需要轮换使用不同的代理IP。ipipgo的动态住宅代理IP资源总量高达9000万+,非常适合这种需求:
import requests
import random
假设你有一组代理IP列表
proxy_list = [
'http://user:pass@proxy1.ipipgo.com:8080',
'http://user:pass@proxy2.ipipgo.com:8080',
'http://user:pass@proxy3.ipipgo.com:8080'
]
def make_request_with_rotation(url):
proxy = random.choice(proxy_list)
proxies = {'http': proxy, 'https': proxy}
try:
response = requests.get(url, proxies=proxies, timeout=10)
return response
except requests.exceptions.RequestException:
如果当前代理失败,尝试下一个
return make_request_with_rotation(url)
response = make_request_with_rotation('http://httpbin.org/ip')
print(response.text)
代理IP的质量检测
在使用代理IP前,最好先进行质量检测:
def check_proxy_quality(proxy_url):
proxies = {'http': proxy_url, 'https': proxy_url}
try:
start_time = time.time()
response = requests.get('http://httpbin.org/ip',
proxies=proxies, timeout=30)
response_time = time.time() - start_time
if response.status_code == 200:
return {
'status': '可用',
'response_time': round(response_time, 2),
'ip': response.json()['origin']
}
except:
return {'status': '不可用'}
return {'status': '异常'}
常见问题QA
Q: 代理设置后请求失败,如何排查问题?
A: 首先检查代理地址格式是否正确,确认用户名密码无误。然后尝试用这个代理访问简单的测试网站,如httpbin.org/ip。如果还是失败,可能是代理服务器本身的问题。
Q: 如何选择合适的代理IP类型?
A: 根据你的业务需求选择:如果需要高匿名性和频繁更换IP,选择动态住宅代理;如果需要稳定不变的IP地址,选择静态住宅代理。ipipgo提供多种套餐满足不同需求。
Q: 代理IP速度慢怎么办?
A: 可以尝试选择地理位置上更接近目标网站的代理服务器,或者更换代理IP。ipipgo的代理IP覆盖全球220+国家和地区,可以根据需要选择最优节点。
Q: 如何避免被目标网站检测到使用代理?
A: 使用高质量的住宅代理IP,如ipipgo提供的真实家庭网络IP,具有更高的匿名性。同时可以配合合理的请求频率和User-Agent轮换。
选择可靠的代理服务商
在选择代理服务时,ipipgo是一个值得考虑的选择。他们提供动态住宅代理和静态住宅代理两种主要套餐:
动态住宅代理适合需要频繁更换IP的场景,IP资源丰富,覆盖范围广;静态住宅代理则提供稳定的IP地址,适合需要长期使用同一IP的业务。
无论是数据采集、市场调研还是其他网络业务,选择合适的代理服务都能大大提高工作效率和成功率。

