You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:20:13