> 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/pt-br/agent-browser/integracao-com-cdp.md).

# Integração com CDP

Conecte frameworks de agentes de IA como Stagehand e browser-use ao Oxylabs Agent Browser.

O Agent Browser expõe um endpoint padrão do Chrome DevTools Protocol (CDP), então qualquer framework que aceite uma URL de CDP pode se conectar sem adaptadores extras. Defina suas credenciais e parâmetros na URL e feche o navegador quando terminar para liberar a sessão.

{% hint style="info" %}
Agentes que tiram uma captura de tela após cada ação enviam grandes volumes de dados. Use timeouts generosos para esses fluxos de trabalho.
{% endhint %}

### Obtendo o ID da sessão

Para abrir a visualização da sessão ao vivo, você precisa do ID da sessão. Com frameworks que não expõem um objeto de sessão CDP, solicite-o com `Runtime.callFunctionOn` e `__session_id` como o quarto argumento. O gateway responde a essa chamada diretamente, então nada é executado na página.

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

Use o `result.value` retornado para montar a URL da visualização ao vivo:

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

Os exemplos a seguir mostram essa chamada em cada framework.

### Stagehand

[Stagehand](https://github.com/browserbase/stagehand) é um framework TypeScript para automação de navegador orientada por IA. Instale com:

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

**Exemplo em 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) é uma biblioteca Python que conecta LLMs à automação de navegador. Instale com:

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

**Exemplo em 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/pt-br/agent-browser/integracao-com-cdp.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.
