> For the complete documentation index, see [llms.txt](https://developers.oxylabs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.oxylabs.io/products/cn/agent-browser.md).

# 代理浏览器

基于云的无头浏览器，内置自适应安全、CAPTCHA 管理和住宅代理。使用代码示例进行测试，并通过高级功能进行自定义。

Agent Browser 允许你在不本地管理的情况下，运行并控制用于基于浏览器的自动化、测试和网页抓取的远程实例。它提供内置的自适应安全、自动 CAPTCHA 处理、地理定位、集成的住宅代理、会话录制、粘性会话和持久配置文件。

## 支持的库

Agent Browser 可与任何支持以下协议的库配合使用 **Chrome DevTools Protocol (CDP)**，包括：

* [Playwright](https://playwright.dev/) （Python 和 Node.js）
* [Puppeteer](https://pptr.dev/) （Node.js）
* 诸如以下的 AI 代理框架： [Stagehand](https://github.com/browserbase/stagehand) 和 [browser-use](https://github.com/browser-use/browser-use)。参见 [CDP 集成](/products/cn/agent-browser/cdp-ji-cheng.md).
* 其他兼容 CDP 的自动化框架

## 连接详情

<table><thead><tr><th width="161">字段</th><th>说明</th></tr></thead><tbody><tr><td><strong>协议</strong></td><td><code>wss://</code> （WebSocket 安全）</td></tr><tr><td><strong>主机（Chromium）</strong></td><td><code>hb.oxylabs.io</code></td></tr><tr><td><strong>身份验证</strong></td><td>在 URL 中，用户信息 – <code>wss://USERNAME:PASSWORD@host</code>。必须包含用户名后缀令牌（例如 <code>user_ab12</code>）。构建自定义 <code>Authorization</code> 不建议。</td></tr><tr><td><strong>传输</strong></td><td>CDP – <code>chromium.connectOverCDP</code> （Playwright）/ <code>puppeteer.connect</code> （Puppeteer）。</td></tr><tr><td><strong>域名</strong></td><td><code>oxylabs.io</code> – 用于连接端点（例如 <a href="http://hb.oxylabs.io">hb.oxylabs.io</a>），仪表板（<a href="http://hb.oxylabs.io/dashboard">hb.oxylabs.io/dashboard</a>），以及会话检查（<a href="http://hb.oxylabs.io/novnc">hb.oxylabs.io/novnc</a>).</td></tr><tr><td><strong>速率限制</strong></td><td><code>100</code> 并发会话， <code>10</code> 每秒会话。 <a href="#need-a-feature-enabled-1">查看更多</a>.</td></tr></tbody></table>

## 功能

Oxylabs Agent Browser 包含内置的、云原生的功能，可通过向你的 WebSocket 连接 URL 添加查询参数来使用。

<table data-header-hidden><thead><tr><th width="250"></th><th></th></tr></thead><tbody><tr><td><a href="/products/cn/agent-browser/ye-mian-chu-li-cheng-xu.md"><strong>页面处理程序</strong></a></td><td>自动识别每个页面，处理受支持的挑战并跟踪页面状态（默认—关闭）。</td></tr><tr><td><a href="/products/cn/agent-browser/captcha-handling.md"><strong>CAPTCHA 处理</strong></a></td><td>自动识别页面并处理访问挑战（默认—关闭）。</td></tr><tr><td><a href="/products/cn/agent-browser/yin-qing-yu-zhi-wen.md"><strong>引擎与指纹</strong></a></td><td>选择浏览器引擎和指纹配置文件。</td></tr><tr><td><a href="/products/cn/agent-browser/geolocation-and-proxy-selection.md"><strong>代理和地理位置定位</strong></a></td><td>通过指定国家、州或城市路由会话。</td></tr><tr><td><a href="/products/cn/agent-browser/device-type.md"><strong>设备模拟</strong></a></td><td>模拟设备特定的指纹和视口。</td></tr><tr><td><a href="/products/cn/agent-browser/session-inspection-and-recording.md#session-inspection-vnc"><strong>会话检查（VNC）</strong></a></td><td>监控实时无头浏览器会话。</td></tr><tr><td><a href="/products/cn/agent-browser/session-inspection-and-recording.md#session-recording"><strong>会话录制</strong></a></td><td>以视频格式录制浏览器会话。</td></tr><tr><td><a href="/products/cn/agent-browser/persistent-sessions-and-profiles.md#persistent-sessions"><strong>持久会话</strong></a></td><td>创建并管理粘性浏览器实例。</td></tr><tr><td><a href="/products/cn/agent-browser/persistent-sessions-and-profiles.md#persistent-profiles"><strong>持久配置文件</strong></a></td><td>在会话之间保存和恢复 Cookie/localStorage。</td></tr></tbody></table>

{% hint style="success" %}
**在使用 AI 编码助手？** 设置 [Agent 技能](/ai-workflows/agent-skills.md) 或 [MCP 服务器](/ai-workflows/mcp.md).
{% endhint %}

### 传递参数

所有功能都可通过在你的 WebSocket Secure 端点后直接追加查询参数来启用和配置，方法是使用 & 连接多个功能。`&`).

```bash
# Example: Connecting to Chrome with US Geolocation and CAPTCHA handling enabled
wss://USER:PASS@hb.oxylabs.io?p_cc=US&solve_captcha=true
```

## 集成

<table data-header-hidden><thead><tr><th width="154.5"></th><th></th></tr></thead><tbody><tr><td><a href="/products/cn/agent-browser/cdp-ji-cheng.md"><strong>CDP 集成</strong></a></td><td>连接 Stagehand 和 browser-use 以打开实时会话检查。</td></tr><tr><td><a href="/ai-workflows/agent-skills.md"><strong>Agent 技能</strong></a></td><td>在 Claude Code、Cursor 和其他 AI 编码助手中设置 Agent Browser。</td></tr><tr><td><a href="/ai-workflows/mcp.md"><strong>MCP 服务器</strong></a></td><td>为兼容 MCP 的 AI 助手提供一个远程 Agent Browser。</td></tr></tbody></table>

## 代码示例

以下是初始化云托管浏览器会话的基本示例：

{% tabs %}
{% tab title="Python（Playwright）" %}

```python
from playwright.sync_api import sync_playwright

username = "USERNAME" # include any account suffix
password = "PASSWORD"
endpoint = "hb.oxylabs.io"
browser_url = f"wss://{username}:{password}@{endpoint}?p_cc=US"

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(browser_url)
    page = browser.new_page()
    page.goto("https://ip.oxylabs.io/location")
    print(page.title())
    browser.close()
```

{% endtab %}

{% tab title="JavaScript（Playwright）" %}

```javascript
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; //For testing only
import { chromium } from "playwright";

const username = "USERNAME";
const password = "PASSWORD";
const endpoint = "hb.oxylabs.io";
const browserUrl = `wss://${username}:${password}@${endpoint}?p_cc=US`;

(async () => {
    const browser = await chromium.connectOverCDP(browserUrl);
    const ctx = browser.contexts()[0] || (await browser.newContext());
    const page = ctx.pages()[0] || (await ctx.newPage());
    await page.goto("https://ip.oxylabs.io/location");
    console.log(await page.title());
    await browser.close();
})();
```

{% endtab %}

{% tab title="JavaScript（Puppeteer）" %}

```javascript
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; //For testing only
import puppeteer from "puppeteer";

const username = "USERNAME";
const password = "PASSWORD";
const endpoint = "hb.oxylabs.io";
const browserUrl = `wss://${username}:${password}@${endpoint}?p_cc=US`;

(async () => {
    const browser = await puppeteer.connect({ browserWSEndpoint: browserUrl });
    const page = await browser.newPage();
    await page.goto("https://ip.oxylabs.io/location");
    console.log(await page.title());
    await browser.close();
})();
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**注意：** 示例使用 `USERNAME` 和 `PASSWORD` 仅为可读性使用。在实际项目中，请从环境变量中加载它们（例如 `process.env.OXYLABS_USERNAME` / `process.env.OXYLABS_PASSWORD`）通过 `.env` 文件。
{% endhint %}

{% hint style="warning" %}
**JavaScript：** 使用 `NODE_TLS_REJECT_UNAUTHORIZED="0"` 在 Node.js 中 require Playwright 之前使用该标志，如果遇到 TLS/证书错误。仅用于本地测试。在生产环境中，应将信任范围限定到特定连接，或改为将提供程序的 CA 证书添加到你的信任存储中。
{% endhint %}

## 参数参考 <a href="#need-a-feature-enabled" id="need-a-feature-enabled"></a>

<table><thead><tr><th width="184">参数</th><th width="467">说明</th><th>类型</th></tr></thead><tbody><tr><td><code>p_cc</code></td><td>国家地理位置，采用 <code>ISO 3166-1 alpha-2</code> 2 位字母代码（例如 <code>US</code>, <code>DE</code>).</td><td>字符串</td></tr><tr><td><code>p_state</code></td><td>州地理位置，小写（例如 <code>texas</code>）。如果两者都使用，则会覆盖 <code>p_cc</code> 。 <a href="https://content.gitbook.com/content/BQ7Zf9paoN3FTeGcyfY1/blobs/cVjpiu1GKicluiVIT9og/us_states.txt">受支持的州列表</a>.</td><td>字符串</td></tr><tr><td><code>p_city</code></td><td>城市地理位置，小写， <code>_</code> 空格使用下划线（例如 <code>new_york</code>). <code>p_cc</code> / <code>p_state</code> 必填。</td><td>字符串</td></tr><tr><td><code>p_device</code></td><td>设置设备指纹、视口和用户代理。支持 <code>桌面端</code> （默认）和 <code>移动端</code>.</td><td>字符串</td></tr><tr><td><code>p_src</code></td><td>浏览器引擎。支持 <code>oxybrowser</code> 专有引擎。若省略，则使用标准引擎。参见 <a href="/products/cn/agent-browser/yin-qing-yu-zhi-wen.md">引擎与指纹</a>.</td><td>字符串</td></tr><tr><td><code>p_fp_tag</code></td><td>指纹配置文件： <code>oxyfp_win</code> （默认）， <code>oxyfp_mac</code>, <code>oxyfp_mac_optimized</code> （仅适用于 <code>p_src=oxybrowser</code>), <code>oxyfp_win_v1</code> （旧版）。参见 <a href="/products/cn/agent-browser/yin-qing-yu-zhi-wen.md">引擎与指纹</a>.</td><td>字符串</td></tr><tr><td><code>page_handler</code></td><td>自动识别页面并自动处理访问挑战。默认： <code>false</code>。参见 <a href="/products/cn/agent-browser/ye-mian-chu-li-cheng-xu.md">页面处理程序</a>.</td><td>布尔值</td></tr><tr><td><code>solve_captcha</code></td><td>在页面加载时自动、实时解决 CAPTCHA。默认： <code>false</code>.</td><td>布尔值</td></tr><tr><td><code>record</code></td><td>录制无头会话视频。默认： <code>false</code>.</td><td>布尔值</td></tr><tr><td><code>record_name</code></td><td>为便于查找而命名录制文件（<code>^[a-zA-Z0-9_-]{1,64}$</code>).</td><td>字符串</td></tr><tr><td><code>session_name</code></td><td>粘性会话。重新连接到同一个在线远程浏览器（<code>^[A-Za-z0-9-]{3,36}$</code>，支持连字符，不支持下划线）。最长 TTL – 24 小时。</td><td>字符串</td></tr><tr><td><code>keep_alive</code></td><td>设置为 <code>true</code>时，在客户端断开连接后保持远程浏览器实例在线。需要 <code>session_name</code>。默认： <code>false</code>.</td><td>布尔值</td></tr><tr><td><code>o_profile</code></td><td>持久配置文件——保存/恢复 Cookie 和 <code>localStorage</code> ，使用命名配置文件（<code>^[a-zA-Z0-9][a-zA-Z0-9_-]{2,35}$</code>).</td><td>字符串</td></tr><tr><td><code>o_profile_save</code></td><td>持久配置文件——在会话期间或结束时强制保存配置文件。需要 <code>o_profile</code>。默认： <code>false</code>.</td><td>布尔值</td></tr><tr><td><code>proxy_resi_ses_id</code></td><td>用于固定跨会话住宅出口 IP 的自定义会话 ID（<code>^[A-Za-z0-9]{3,36}$</code>).</td><td>字符串</td></tr><tr><td><code>proxy_resi_ses_time</code></td><td>保持固定住宅代理出口 IP 的时长（分钟）。最小 <code>1</code>，最大 <code>1440</code> （24 小时）。</td><td>整数</td></tr></tbody></table>

## 推荐设置

### 优化流量

抓取动态页面通常会导致浏览器下载不必要的资源，例如大型媒体、跟踪脚本、图片和字体。这会消耗带宽并降低执行速度。

你可以在这些请求消耗资源之前，以编程方式拦截并中止它们：

{% tabs %}
{% tab title="Python (Playwright)" %}

```python
# Abort heavy assets to save bandwidth and improve speeds
def block_resources(route):
    if route.request.resource_type in ["image", "stylesheet", "media", "font"]:
        route.abort()
    else:
        route.continue_()

page.route("**/*", block_resources)
```

{% endtab %}

{% tab title="JavaScript（Playwright）" %}

```javascript
// Abort heavy assets to save bandwidth and improve speeds
await page.route("**/*", (route) => {
    const type = route.request().resourceType();
    if (["image", "stylesheet", "media", "font"].includes(type)) {
        return route.abort();
    }
    return route.continue();
});
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
如果使用 Page Handler，请不要为目标阻止样式表、图片、媒体或字体。阻止它们可能会导致挑战控件无法加载。
{% endhint %}

### 错误处理和重试 <a href="#error-handling-and-retries" id="error-handling-and-retries"></a>

网络波动和每秒 10 个会话的速率限制意味着单个 `connectOverCDP` 调用可能会暂时失败。请将连接包装在 `重试` 和指数 `退避`中，并为每次尝试设置超时。下面的示例使用标准 Playwright API。

```javascript
const { chromium } = require("playwright");

const MAX_RETRIES = 5;
const BASE_DELAY_MS = 1000;

async function connectWithRetry(endpoint, { maxRetries = MAX_RETRIES } = {}) {
    let lastError;
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            // Cap how long a single connection attempt may take.
            return await chromium.connectOverCDP(endpoint, { timeout: 60_000 });
        } catch (err) {
            lastError = err;
            // Exponential backoff with jitter — backs off when you hit the
            // 10-new-sessions/second rate limit instead of hammering the endpoint.
            const delay = BASE_DELAY_MS * 2 ** attempt + Math.random() * 250;
            console.warn(
                `connect attempt ${attempt + 1} failed: ${err.message}; ` +
                `retrying in ${Math.round(delay)}ms`
            );
            await new Promise((resolve) => setTimeout(resolve, delay));
        }
    }
    throw lastError;
}
```

{% hint style="info" %}
有关握手、WebSocket 关闭和页面内错误的完整列表，请参见 [响应代码](/products/cn/agent-browser/xiang-ying-dai-ma.md).
{% endhint %}

### 资源清理 <a href="#resource-cleanup" id="resource-cleanup"></a>

完成后务必关闭浏览器，即使你的自动化在中途抛出异常。使用 `try { ... } finally { ... }` 代码块，以确保清理在所有路径上运行：

```javascript
const browser = await connectWithRetry(endpoint);
try {
    const ctx = browser.contexts()[0] || (await browser.newContext());
    const page = ctx.pages()[0] || (await ctx.newPage());
    await page.goto("https://ip.oxylabs.io/location");
    // ... your automation ...
} finally {
    // Runs even if the block above throws. Without this, a session left open
    // after an exception lingers and counts against your 100 concurrent-session limit.
    await browser.close();
}
```

如果在 connect 和 close 之间发生异常且你未进行清理，远程会话将保持开启，并占用你的一个 **100 个并发会话** 配额，直到它被回收。在高负载下泄漏会话会耗尽限制并阻止新连接。

## 需要启用某项功能？ <a href="#need-a-feature-enabled" id="need-a-feature-enabled"></a>

某些 Agent Browser 功能默认受限。如需调整限制，请联系 Oxylabs 支持（[在线聊天](https://oxylabs.io/) 或 [电子邮件](mailto:support@oxylabs.io)）或您的专属客户经理：

* **更多持久化配置文件** – 将您的账户默认保存配置文件上限提高到 5 个以上。
* **更多持久化会话** – 将您的账户默认 5 个并发持久化会话上限提高。
* **受限目标** – 通过 KYC 流程解锁更多目标类别。
* **更高的速率限制** – 提高到超过 100 个并发会话 / 每秒 10 个。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers.oxylabs.io/products/cn/agent-browser.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
