> 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/cdp-ji-cheng.md).

# CDP 集成

将 Stagehand 和 browser-use 等 AI 代理框架连接到 Oxylabs Agent Browser。

Agent Browser 提供标准的 Chrome DevTools Protocol (CDP) 端点，因此任何接受 CDP URL 的框架都可以无需额外适配器直接连接。在 URL 中设置你的凭据和参数，完成后关闭浏览器以释放会话。

{% hint style="info" %}
在每个操作后都截图的代理会发送大量数据。对此类工作流请使用较长的超时时间。
{% endhint %}

### 获取会话 ID

要打开实时会话视图，你需要会话 ID。对于不暴露 CDP 会话对象的框架，请使用以下方式请求它： `Runtime.callFunctionOn` 和 `__session_id` 作为第四个参数。网关会直接响应此调用，因此页面中不会执行任何内容。

```json
{
  "method": "Runtime.callFunctionOn",
  "params": {
    "functionDeclaration": "function () {}",
    "arguments": [{}, {}, {}, { "value": "__session_id" }]
  }
}
```

使用返回的 `result.value` 来构建实时视图 URL：

```
https://hb.oxylabs.io/novnc/?id=SESSION_ID
```

以下示例展示了在各个框架中如何进行此调用。

### Stagehand

[Stagehand](https://github.com/browserbase/stagehand) 是一个用于 AI 驱动浏览器自动化的 TypeScript 框架。使用以下命令安装：

```bash
npm install @browserbasehq/stagehand
```

**TypeScript 示例：**

```typescript
import { Stagehand } from "@browserbasehq/stagehand";

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

async function main() {
    const stagehand = new Stagehand({
        env: "LOCAL",
        localBrowserLaunchOptions: { cdpUrl },
        model: "anthropic/claude-sonnet-5-5", // requires ANTHROPIC_API_KEY
    });
    await stagehand.init();
    const page = stagehand.context.pages()[0];

    // Get the session ID and print the live view link
    const { result } = await page.sendCDP<{ result: { value: string } }>(
        "Runtime.callFunctionOn",
        {
            functionDeclaration: "function () {}",
            arguments: [{}, {}, {}, { value: "__session_id" }],
        }
    );
    console.log(`Live view: https://hb.oxylabs.io/novnc/?id=${result.value}`);

    await page.goto("https://news.ycombinator.com");
    await stagehand.act("Click on the #1 ranked story link");

    await stagehand.close();
}

main().catch(console.error);
```

### browser-use

[browser-use](https://github.com/browser-use/browser-use) 是一个将 LLM 连接到浏览器自动化的 Python 库。使用以下命令安装：

```bash
pip install browser-use langchain-anthropic
```

**Python 示例：**

```python
import asyncio
from browser_use import Agent, Browser
from langchain_anthropic import ChatAnthropic  # requires ANTHROPIC_API_KEY

username = "USERNAME"
password = "PASSWORD"
cdp_url = f"wss://{username}:{password}@hb.oxylabs.io?p_cc=US"


async def get_session_id(browser: Browser) -> str:
    cdp_session = await browser.get_or_create_cdp_session()
    result = await cdp_session.cdp_client.send.Runtime.callFunctionOn(
        params={
            "functionDeclaration": "function () {}",
            "arguments": [{}, {}, {}, {"value": "__session_id"}],
        },
        session_id=cdp_session.session_id,
    )
    return result["result"]["value"]


async def main():
    browser = Browser(cdp_url=cdp_url)
    await browser.start()  # CDP is available after the session connects

    session_id = await get_session_id(browser)
    print(f"Live view: https://hb.oxylabs.io/novnc/?id={session_id}")

    agent = Agent(
        task="Find the number 1 post on Show HN",
        llm=ChatAnthropic(model_name="claude-sonnet-5-5"),
        browser=browser,
    )
    print(await agent.run())

    await browser.kill()


if __name__ == "__main__":
    asyncio.run(main())
```


---

# 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/cdp-ji-cheng.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.
