集成

在代码中使用代理

常用 HTTP 客户端的可运行示例。把 USER、PASS、HOST 和 PORT 替换为订单中的值,或替换为生成器中的一行住宅代理。

更新于 2026年10月16日

HTTP 和 HTTPS#

curl -x http://USER:PASS@HOST:PORT https://api.ipify.org

SOCKS5#

在 ISP 和数据中心上,SOCKS5 端口等于 HTTP 端口加一。住宅代理请使用 SOCKS5 端口,例如 1080。

curl -x socks5h://USER:PASS@HOST:PORT https://api.ipify.org

Python#

使用会话的 requests

会话会复用连接,因此在登录或结账过程中,目标网站始终看到同一个 IP 和同一个 TLS 握手。

Python
import requests

proxy = "http://USER:PASS@HOST:PORT"
s = requests.Session()
s.proxies = {"http": proxy, "https": proxy}

for url in urls:
    r = s.get(url, timeout=30)
    print(r.status_code, len(r.content))

httpx

Python
# pip install httpx            (SOCKS5: pip install "httpx[socks]")
import httpx

with httpx.Client(proxy="http://USER:PASS@HOST:PORT", timeout=30) as client:
    print(client.get("https://api.ipify.org?format=json").json())

aiohttp

Python
import asyncio
import aiohttp

PROXY = "http://USER:PASS@HOST:PORT"

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.ipify.org?format=json", proxy=PROXY) as r:
            print(await r.json())

asyncio.run(main())

aiohttp 本身只支持 HTTP 代理。使用 SOCKS5 需要加上 aiohttp-socks:

Python
# pip install aiohttp-socks
import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector

async def main():
    connector = ProxyConnector.from_url("socks5://USER:PASS@HOST:PORT", rdns=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get("https://api.ipify.org?format=json") as r:
            print(await r.json())

asyncio.run(main())

Scrapy

Scrapy 内置的代理中间件从 meta 读取代理,并发送 URL 中的凭据。使用轮换的住宅字符串时,每个请求都会自动从新地址发出。

Python
# spider.py
import scrapy

class IpSpider(scrapy.Spider):
    name = "ip"

    def start_requests(self):
        for _ in range(3):
            yield scrapy.Request(
                "https://api.ipify.org?format=json",
                meta={"proxy": "http://USER:PASS@HOST:PORT"},
                dont_filter=True,
            )

    def parse(self, response):
        yield response.json()

Node.js#

axios

axios 有自己的 proxy 选项,但用它隧道传输 HTTPS 并不可靠。请改为给它一个 agent,并关闭它自带的代理功能:

JavaScript
// npm install axios https-proxy-agent
import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";

const agent = new HttpsProxyAgent("http://USER:PASS@HOST:PORT");

const { data } = await axios.get("https://api.ipify.org?format=json", {
  httpsAgent: agent,
  proxy: false, // let the agent do the proxying
});
console.log(data);

超时与重试#

  • 始终设置超时。30 秒适合大多数目标。
  • 遇到连接错误、超时以及 502、503、504 时重试,并逐步加长等待。不要重试 407:错误的凭据不会自己变对。
  • 在住宅代理上,用新的固定会话重试会落到一台新设备上。见 在代码中使用会话。
  • 限制重试次数。对被封锁的目标无限重试只会白白消耗流量。
Python
import time
import requests

def fetch(url: str, proxy: str, attempts: int = 3) -> requests.Response:
    for i in range(attempts):
        try:
            r = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=30)
            if r.status_code in (502, 503, 504):
                raise requests.HTTPError(r.status_code)
            return r
        except (requests.ConnectionError, requests.Timeout, requests.HTTPError):
            if i == attempts - 1:
                raise
            time.sleep(2 ** i)  # 1 s, 2 s, 4 s

没有找到答案?

网站在线客服 24 小时回复。通过 Telegram 联系通常最快,提交工单会通过邮件回复。