新品不限流量住宅代理:固定价格,流量不计量。 低至 $33.25/天

Python · 集成指南

如何在 Python Requests 中使用代理

Requests 只需一个 proxies 字典,即可通过 Proxonym 发送流量。本指南涵盖身份认证、地理定位、轮换 IP 与粘性 IP、SOCKS5,以及网关错误的重试。

  • 共 6 步
  • 12 分钟完成配置
  • 复制即用的代码

开始之前

  • Python 3.10 或更高版本
  • Requests 2.x;如需 SOCKS5,还需安装 socks 可选依赖
  • Proxonym 住宅代理或移动代理套餐
获取代理凭据

已是客户?您的用户名和密码就在控制台中。

  1. 安装 Requests

    使用 pip 安装 Requests。socks 可选依赖会一并安装 PySocks,只有使用 SOCKS5 端点时才需要它。

    Shell
    python -m pip install requests
    python -m pip install "requests[socks]"   # only for SOCKS5
  2. 通过网关发送请求

    将凭据写入代理 URL,并将其同时用于 http 和 https 两个键。HTTPS 目标通过 CONNECT 隧道传输,因此代理 URL 本身仍使用 http:// 协议前缀。

    Python
    import requests
    
    PROXY = "http://USERNAME:PASSWORD@gw.proxonym.com:8000"
    proxies = {"http": PROXY, "https": PROXY}
    
    response = requests.get("https://api.ipify.org", proxies=proxies, timeout=60)
    print("Exit IP:", response.text)
  3. 定位国家、州、城市或 ASN

    这个辅助函数会根据关键字参数,按网关要求的顺序构建用户名。使用小写的 ISO 国家代码,空格用下划线代替,州和城市二选一,不要同时指定。

    Python
    import requests
    
    
    def proxy_for(**params):
        """proxy_for(country="us", city="new_york", session="a7k2", lifetime=30)"""
        user = "USERNAME"
        for key in ("country", "state", "city", "asn", "session", "lifetime"):
            if key in params:
                user += f"-{key}-{params[key]}"
        url = f"http://{user}:PASSWORD@gw.proxonym.com:8000"
        return {"http": url, "https": url}
    
    
    for proxies in (
        proxy_for(country="us", city="new_york"),
        proxy_for(country="de", state="bavaria"),
        proxy_for(country="us", asn=7922),
    ):
        info = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=60).json()
        print(info["ip"], info.get("city"), info.get("country"))
  4. 轮换 IP 或保持同一 IP

    不带会话参数时,每个新连接都会获得一个新 IP,而 requests.get() 每次调用都会建立新连接。复用上一步的 proxy_for(),添加一个最多 32 位字母和数字的会话 ID,即可将同一 IP 最长保持 120 分钟。

    Python
    import secrets
    
    import requests
    
    # Rotating: a new exit IP on every call
    for _ in range(3):
        print(requests.get("https://api.ipify.org", proxies=proxy_for(country="us"), timeout=60).text)
    
    # Sticky: the same exit IP for up to 30 minutes
    sticky = proxy_for(country="us", session=secrets.token_hex(4), lifetime=30)
    for _ in range(3):
        print(requests.get("https://api.ipify.org", proxies=sticky, timeout=60).text)
  5. 使用 SOCKS5 端点

    安装 PySocks 后,将两个键都指向 1080 端口。socks5h:// 协议前缀会在代理端解析主机名,使 DNS 查询不经过您自己的网络。

    Python
    import requests
    
    PROXY = "socks5h://USERNAME-country-gb:PASSWORD@gw.proxonym.com:1080"
    proxies = {"http": PROXY, "https": PROXY}
    
    print(requests.get("https://api.ipify.org", proxies=proxies, timeout=60).text)
  6. 重试网关错误

    为暂时性故障挂载重试策略,并捕获 ProxyError:网关拒绝建立隧道时,Requests 会抛出该异常。重试无法解决 407、402 或 403,请先修正凭据、余额或目标网站方面的问题。

    Python
    import requests
    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
    
    retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 502, 504])
    session = requests.Session()
    session.mount("http://", HTTPAdapter(max_retries=retry))
    session.mount("https://", HTTPAdapter(max_retries=retry))
    
    PROXY = "http://USERNAME-country-us:PASSWORD@gw.proxonym.com:8000"
    proxies = {"http": PROXY, "https": PROXY}
    
    try:
        response = session.get("https://example.com", proxies=proxies, timeout=(10, 60))
        response.raise_for_status()
        print(response.status_code, len(response.text))
    except requests.exceptions.ProxyError as exc:
        # The message includes the gateway status, for example 407 or 502
        print("Gateway refused the tunnel:", exc)
    except requests.exceptions.RequestException as exc:
        print("Request failed:", exc)

常见问题

为什么 Requests 报错“Tunnel connection failed: 407”?

网关拒绝了代理 URL 中的凭据。请从控制台重新复制用户名和密码,用短横线连接定位参数,并对密码中的特殊字符进行 URL 编码。如果同一段代码在一台机器上正常、在另一台上却失败,请检查是否有 HTTPS_PROXY 环境变量覆盖了您的设置。

Requests 支持 SOCKS5 代理吗?

支持,只需用 pip install "requests[socks]" 安装 socks 可选依赖(会一并安装 PySocks)。使用 socks5h://USERNAME:PASSWORD@gw.proxonym.com:1080,让主机名在代理端解析。定位参数和会话参数的用法与 HTTP 端点相同,因此切换协议时无需修改用户名。

如何并行发送大量请求?

Requests 是同步库,因此请在 ThreadPoolExecutor 中执行调用,或改用 httpx、aiohttp 等异步客户端。Proxonym 不限并发会话数,每个账户的突发请求上限约为每秒 10,000 次,因此实际瓶颈通常在目标网站。如果某个工作线程需要稳定的 IP,请为它分配独立的会话 ID。

可以用 httpx 或 aiohttp 代替 Requests 吗?

可以。在 httpx 中,创建 Client 或 AsyncClient 时传入 proxy="http://USERNAME:PASSWORD@gw.proxonym.com:8000"。在 aiohttp 中,将同一个 URL 作为每个请求的 proxy 参数传入。这两个库都会使用连接池,因此复用同一连接的请求,在连接关闭前都会沿用同一个出口 IP。

准备好接入了吗?立即获取凭据

选择套餐,从控制台复制用户名和密码,然后运行上面的代码。

  • 按量付费
  • 即时开通
  • 支持加密货币
  • 不自动续费