Python使用代理请求触发InvalidURL解析失败问题求助
问题解决:代理URL格式错误导致的InvalidURL
你的核心问题是代理地址的拼接顺序完全错误,从报错信息能看到生成的代理URL是https://***.***.***.***:****:@*****:*****,把认证信息放在了端口后面还多了冗余冒号,完全不符合HTTP代理的格式规范。
正确的代理格式
带用户名密码认证的代理URL标准格式为:协议://用户名:密码@代理IP:端口
修正后的代码
import requests def testSingleProxy(ip, port, user, passw): url = 'https://stackoverflow.com/' # example # 按正确顺序拼接代理地址 proxy_auth = f"{user}:{passw}@{ip}:{port}" http_proxy = f'http://{proxy_auth}' https_proxy = f'https://{proxy_auth}' proxies = { 'http': http_proxy, 'https': https_proxy, } try: response = requests.get(url, proxies=proxies, timeout=10) response.raise_for_status() # 主动抛出HTTP状态码异常 return response except requests.exceptions.RequestException as e: print(f"请求出错: {e}") return None
额外注意事项
- 如果用户名或密码包含
@、:、/这类特殊字符,需要用urllib.parse.quote做URL编码,否则仍会解析失败:from urllib.parse import quote user_encoded = quote(user) passw_encoded = quote(passw) proxy_auth = f"{user_encoded}:{passw_encoded}@{ip}:{port}" - 加入
try-except捕获请求过程中的超时、连接失败等异常,避免程序直接崩溃。
内容的提问来源于stack exchange,提问作者Luca Orlandi
相关产品推荐
相关产品推荐

