使用Python Requests配置代理后IP未变更的问题求助
问题排查与解决方法
1. 代理字典键格式错误(核心问题)
你的代码中代理字典的键多了冒号:'http:'和'https:',而Requests库要求proxies字典的键必须是'http'或'https'(无冒号)。带冒号的键会被Requests忽略,导致请求根本没走指定的代理,直接用了直连或系统代理。
修正后的代理字典:
proxy = { 'http': 'http://31.186.239.244:8080', 'https': 'http://31.186.239.244:8080' }
2. 排除系统代理干扰
Requests默认会读取系统的代理设置,如果你Windows里配置了代理,即使代码中没指定proxies,请求也会走系统代理,导致两次请求IP相同。测试无代理场景时,要强制禁用代理:
# 强制不使用任何代理,确保请求直连 old_ip = requests.get("https://2ip.ru", proxies={"http": None, "https": None})
3. 用更可靠的测试站点验证代理
2ip.ru可能存在缓存或CDN缓存IP的情况,建议用httpbin.org/ip来测试,它会直接返回当前请求的IP,结果更准确:
# 测试直连IP response = requests.get("https://httpbin.org/ip", proxies={"http": None, "https": None}) print("直连IP:", response.json()["origin"]) # 测试代理IP response_proxy = requests.get("https://httpbin.org/ip", proxies=proxy, headers=headers) print("代理IP:", response_proxy.json()["origin"])
4. 检查代理是否需要认证
如果你的代理需要用户名密码,Windows可能已经保存了认证信息,但代码中需要显式添加:
# 带认证的代理格式 proxy = { 'http': 'http://username:password@31.186.239.244:8080', 'https': 'http://username:password@31.186.239.244:8080' }
5. 禁用请求缓存
在headers中添加缓存禁用字段,避免网站返回缓存的IP数据:
headers = { # 原有header内容... 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' }
内容的提问来源于stack exchange,提问作者l0cus
相关产品推荐
相关产品推荐

