# 数据中心代理代码示例：curl、Python、Node.js 和 Playwright

> curl、Python requests 和 aiohttp、Node.js undici 和 Playwright、HTTP 和 SOCKS5 的代理代码示例。RackProxies：每个 IP US$1.29 起，无需 KYC，支持加密货币。

- URL: https://rackproxies.com/zh/docs/code-examples/
- 最后更新: 2026-10-19
- Publisher: RackProxies (https://rackproxies.com)

为最常见客户端准备的复制即用代码片段，每个都经过语法测试。所有示例都指向 api.ipify.org、httpbin.org/ip 或 example.com。

**快速回答 — 如何在代码中使用数据中心代理？**

这些代理代码示例会把一个 `http://USERNAME:PASSWORD@IP:PORT` URL 传给客户端：curl 用 `-x`，Python requests 用 `proxies=`，Node.js 用 `ProxyAgent`，Playwright 用 `proxy` 选项。SOCKS5 使用 `socks5h://`。**RackProxies** 的 IP 支持 HTTP、HTTPS（CONNECT）和 SOCKS5，每个专用 IPv4 30 天 US$1.29 起。无需 KYC，仅支持加密货币。

## 我需要哪个代码片段？

*每个代码片段中的文档地址 203.0.113.24 和端口 8000：请替换为你账户中的一条线路。*

| 客户端 | HTTP 代理 | SOCKS5 代理 | 额外依赖包 |
| --- | --- | --- | --- |
| curl | `-x http://…` | `-x socks5h://…` | 无 |
| Python requests | `proxies={…}` | `socks5h://` URL | SOCKS5 需要 `requests[socks]` |
| Python aiohttp | `proxy=` 和 `proxy_auth=` | 非内置 | SOCKS5 需要 `aiohttp-socks` |
| Node.js fetch | undici `ProxyAgent` | 非内置 | `undici` |
| Node.js https | `https-proxy-agent` | `socks-proxy-agent` | 两者之一 |
| Playwright | `proxy: { server, username, password }` | 使用 HTTP 或允许列表 | `playwright` |

## 如何在 curl 中使用代理？

用 `-x` 传入代理 URL。curl 会自行处理 `https://` 目标的 CONNECT 隧道。本页所有片段都使用文档地址 `203.0.113.24`；[连接格式](https://rackproxies.com/zh/docs/connection-format/)页面说明了如何用你的线路构建该 URL。

*curl：HTTP、SOCKS5、独立登录、允许列表*

```bash
# HTTP proxy, HTTPS target (CONNECT tunnel)
curl -x http://USERNAME:PASSWORD@203.0.113.24:8000 https://api.ipify.org

# SOCKS5, hostname resolved by the proxy
curl -x socks5h://USERNAME:PASSWORD@203.0.113.24:8000 https://api.ipify.org

# Login passed separately (no URL-encoding needed)
curl -x http://203.0.113.24:8000 -U 'USERNAME:PASSWORD' https://httpbin.org/ip

# IP allowlist: no login
curl -x http://203.0.113.24:8000 https://api.ipify.org

# Show the proxy handshake and the timings
curl -v -s -o /dev/null -w '%{time_connect} %{time_appconnect} %{time_total}\n' \
  -x http://USERNAME:PASSWORD@203.0.113.24:8000 https://example.com
```

## 如何在 Python requests 中使用代理？

给 requests 一个 `proxies` 字典，其中 `http` 和 `https` 使用同一个 URL。`https` 键用于 `https://` 目标；它的值仍以 `http://` 开头，因为它描述的是到代理的连接。当代理拒绝连接或登录时，requests 会抛出 `ProxyError`。

*通过 HTTP 代理使用 requests，并处理错误*

```python
import requests  # pip install requests

# From the line 203.0.113.24:8000:USERNAME:PASSWORD in your account
proxy = 'http://USERNAME:PASSWORD@203.0.113.24:8000'
proxies = {'http': proxy, 'https': proxy}

try:
    response = requests.get('https://api.ipify.org', proxies=proxies, timeout=20)
    response.raise_for_status()
    print('Exit IP:', response.text)
except requests.exceptions.ProxyError as error:
    print('Proxy problem (credentials, port or allowlist):', error)
except requests.exceptions.Timeout:
    print('No answer within 20 seconds')
```

*通过 SOCKS5 发送请求（pip install "requests[socks]")*

```python
import requests  # pip install "requests[socks]"

# socks5h: the proxy resolves the hostname. Use the SOCKS5 port shown in your account.
proxy = 'socks5h://USERNAME:PASSWORD@203.0.113.24:8000'
proxies = {'http': proxy, 'https': proxy}

response = requests.get('https://httpbin.org/ip', proxies=proxies, timeout=20)
print(response.json())  # {'origin': '203.0.113.24'}
```

*一个会话，通过一个 IP 发送多个请求*

```python
import requests

# A Session reuses connections: faster for many requests through the same IP.
session = requests.Session()
session.proxies.update({
    'http': 'http://USERNAME:PASSWORD@203.0.113.24:8000',
    'https': 'http://USERNAME:PASSWORD@203.0.113.24:8000',
})
session.headers['User-Agent'] = 'my-monitor/1.0 (contact: you@example.com)'

for url in ['https://example.com', 'https://httpbin.org/ip']:
    response = session.get(url, timeout=20)
    print(url, response.status_code, len(response.content), 'bytes')
```

设置一个 `User-Agent`，其中标明你的工具和联系人，如 Session 示例所示：这样网站所有者可以联系你，而不是封锁你。如果没有提供 `proxies` 参数，requests 还会读取 `HTTP_PROXY` 和 `HTTPS_PROXY` 环境变量。

## 如何在 Python aiohttp 中使用代理？

aiohttp 为每个请求单独指定代理：`proxy=` 用于地址，`proxy_auth=` 用于登录信息。它支持 HTTP 代理，包括对 `https://` 目标使用 CONNECT。对于 SOCKS5，需要单独的 `aiohttp-socks` 包。

*通过 HTTP 代理使用 aiohttp*

```python
import asyncio

import aiohttp  # pip install aiohttp (HTTP proxies; SOCKS needs the aiohttp-socks package)

PROXY = 'http://203.0.113.24:8000'
AUTH = aiohttp.BasicAuth('USERNAME', 'PASSWORD')


async def main():
    timeout = aiohttp.ClientTimeout(total=20)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        async with session.get('https://httpbin.org/ip', proxy=PROXY, proxy_auth=AUTH) as response:
            print(await response.json())


asyncio.run(main())
```

## 如何在 Node.js 中使用代理？

Node 内置的 `fetch` 不接受代理参数，因此请使用 `undici` 包，并将其 `ProxyAgent` 作为 `dispatcher`。对于经典的 `https` 模块，HTTP 代理使用 `https-proxy-agent`，SOCKS5 使用 `socks-proxy-agent`。两个代码片段都是 ES 模块：请将它们保存为 `.mjs` 文件。

*使用 undici ProxyAgent 进行 fetch*

```javascript
// npm install undici
import { ProxyAgent, fetch } from 'undici';

const dispatcher = new ProxyAgent({
  uri: 'http://203.0.113.24:8000',
  token: `Basic ${Buffer.from('USERNAME:PASSWORD').toString('base64')}`,
});

const response = await fetch('https://api.ipify.org', { dispatcher });
console.log('Exit IP:', await response.text());
```

*使用 https-proxy-agent 和 socks-proxy-agent 进行 https 请求*

```javascript
// npm install https-proxy-agent socks-proxy-agent
import https from 'node:https';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';

const httpAgent = new HttpsProxyAgent('http://USERNAME:PASSWORD@203.0.113.24:8000');
// Use the SOCKS5 port shown in your account; socks5h lets the proxy resolve DNS.
const socksAgent = new SocksProxyAgent('socks5h://USERNAME:PASSWORD@203.0.113.24:8000');

for (const agent of [httpAgent, socksAgent]) {
  https.get('https://api.ipify.org', { agent }, (res) => {
    res.setEncoding('utf8');
    res.on('data', (chunk) => console.log('Exit IP:', chunk));
  }).on('error', (err) => console.error('Proxy error:', err.message));
}
```

## 如何在 Playwright 中使用代理？

向 `chromium.launch()` 传递一个 `proxy` 对象，其中包含服务器地址，并单独提供用户名和密码。请使用 HTTP 形式：Chromium 内置的 SOCKS5 客户端历来不支持 SOCKS5 代理的用户名和密码认证。如果使用 IP 白名单，请省略 `username` 和 `password`。

*通过 HTTP 代理使用 Playwright (Chromium)*

```javascript
// npm install playwright && npx playwright install chromium
import { chromium } from 'playwright';

const browser = await chromium.launch({
  proxy: { server: 'http://203.0.113.24:8000', username: 'USERNAME', password: 'PASSWORD' },
});
const page = await browser.newPage();
await page.goto('https://api.ipify.org');
console.log('Exit IP:', await page.textContent('body'));
await browser.close();
```

通过代理使用浏览器，对您自己的网站进行 QA、广告和本地化检查以及类似的合法工作。请记住，代理只更改 IP：浏览器的语言和时区仍是您机器的设置，除非您在浏览器上下文中设置它们。

## 如何测量通过代理的延迟？

对几个完整请求计时并取中位数。下面的 Python 代码片段通过一个 IP 向 `https://example.com` 发送五个请求。通过不同数据中心城市的 IP 运行它来比较；[城市指南](https://rackproxies.com/zh/guides/choose-a-datacenter-city/) 解释了每个距离的物理下限。

*通过代理的中位请求时间*

```python
import statistics
import time

import requests

proxy = 'http://USERNAME:PASSWORD@203.0.113.24:8000'
timings = []
for _ in range(5):
    start = time.perf_counter()
    requests.get('https://example.com', proxies={'http': proxy, 'https': proxy}, timeout=20)
    timings.append((time.perf_counter() - start) * 1000)

print(f'median {statistics.median(timings):.0f} ms over {len(timings)} requests')
```

## 如何使用整个 IP 列表？

加载您的 TXT 导出文件，将每一行转换为 URL，并为每个请求选择一个 IP：跨站点轮询，或对同一站点使用同一 IP。[轮换与静态指南](https://rackproxies.com/zh/guides/rotating-vs-static-datacenter-proxies/) 有一个完整的示例，[连接格式](https://rackproxies.com/zh/docs/connection-format/) 页面有一个用于整个列表的转换器。无论您的列表大小如何，请尊重每个站点的节奏：更多的 IP 不会提高站点的限制。

## 代码示例问题

### 为什么当网站是 https:// 时，我使用 http:// 作为代理？

代理 URL 的协议描述的是您与代理之间的连接，而不是与网站之间的连接。您的客户端通过普通 TCP 连接到代理，要求它打开一个 CONNECT 隧道，然后在其中与网站运行 TLS。页面内容保持端到端加密；只有代理登录信息以可读形式传输。

### 我的密码包含特殊字符。会有什么变化？

在 URL 形式中，使用 Python 中的 `urllib.parse.quote(password, safe='')` 或 JavaScript 中的 `encodeURIComponent(password)` 对密码进行编码。单独接受登录信息的客户端，例如 aiohttp 的 `BasicAuth`、Playwright 的 `username` 和 `password`，或 curl 的 `-U`，无需编码。[连接格式](https://rackproxies.com/zh/docs/connection-format/) 页面列出了这些字符。

### 为什么 requests 说它缺少 SOCKS 支持的依赖项？

requests 的 SOCKS 支持位于一个可选的额外项中。使用 `pip install "requests[socks]"` 安装它（会添加 PySocks），并使用 `socks5h://` URL，以便代理解析主机名。HTTP 代理无需任何额外包即可工作，因此您也可以将 URL 切换为 `http://` 并保持依赖项不变。

### 我可以通过一个 IP 并行运行多个请求吗？

可以，在合理使用范围内；我们不公布每个 IP 的连接限制。为了您自身的稳定性，请保持合理的并行度，并遵守每个网站的节奏：对同一网站的并行请求仍会计入其限制。按 IP 计费 30 天，不按 GB 计费，遵循合理使用政策。

### 我的代码应该首先调用哪个测试 URL？

调用 `https://api.ipify.org` 或 `https://httpbin.org/ip`：每个都会返回它看到的 IP，因此您可以确认流量是从您的代理发出的。然后调用您的真实目标。如果测试 URL 有效而目标无效，则问题出在代理和目标之间，而不是您的代码中。

### 这些示例需要 ID 才能获取代理吗？

不需要。无需 KYC：注册、充值或购买均无需身份证件、自拍或签署文件。在 BTC, USDT, USDC, ETH, SOL, LTC 中充值，从 US$1.29 购买套餐，然后将您账户中的行复制到代码片段中。查看 [定价](https://rackproxies.com/zh/pricing/) 了解所有套餐大小。

**使用您自己的 IP 运行示例** 1 IP 用于 US$1.29，包含 HTTP 和 SOCKS5。无需 KYC，可用加密货币支付。 [查看价格](https://rackproxies.com/zh/pricing/) · [快速开始](https://rackproxies.com/zh/docs/quickstart/)

## 参考资料

1. [curl 手册页](https://curl.se/docs/manpage.html) — curl project (2026-10-19)
2. [Requests：代理和 SOCKS](https://requests.readthedocs.io/en/latest/user/advanced/) — Requests (2026-10-19)
3. [aiohttp：代理支持](https://docs.aiohttp.org/en/stable/client_advanced.html) — aiohttp (2026-10-19)
4. [undici：ProxyAgent](https://undici.nodejs.org/) — Node.js (2026-10-19)
5. [proxy-agents（https-proxy-agent、socks-proxy-agent）](https://github.com/TooTallNate/proxy-agents) — GitHub (2026-10-19)
6. [Playwright：HTTP 代理](https://playwright.dev/docs/network) — Playwright (2026-10-19)

---

RackProxies: RackProxies 是一家独享数据中心代理服务商：IPv4 地址按 IP 租用 30 天，支持加密货币支付，无需上传身份证件。页面覆盖 22 个国家和 34 个数据中心城市，并提供公开网络数据。
