> 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/es/agent-browser/integracion-de-cdp.md).

# Integración de CDP

Conecta frameworks de agentes de IA como Stagehand y browser-use con Oxylabs Agent Browser.

Agent Browser expone un endpoint estándar de Chrome DevTools Protocol (CDP), así que cualquier framework que acepte una URL de CDP puede conectarse sin adaptadores adicionales. Establece tus credenciales y parámetros en la URL, y cierra el navegador cuando termines para liberar la sesión.

{% hint style="info" %}
Los agentes que toman una captura de pantalla después de cada acción envían grandes cantidades de datos. Usa timeouts amplios para estos flujos de trabajo.
{% endhint %}

### Obteniendo el ID de sesión

Para abrir la vista de sesión en vivo, necesitas el ID de sesión. Con frameworks que no exponen un objeto de sesión de CDP, solicítalo con `Runtime.callFunctionOn` y `__session_id` como cuarto argumento. El gateway responde a esta llamada directamente, así que no se ejecuta nada en la página.

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

Usa el valor devuelto `result.value` para construir la URL de la vista en vivo:

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

Los siguientes ejemplos muestran esta llamada en cada framework.

### Stagehand

[Stagehand](https://github.com/browserbase/stagehand) es un framework de TypeScript para la automatización del navegador impulsada por IA. Instálalo con:

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

**Ejemplo en 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) es una biblioteca de Python que conecta LLM con la automatización del navegador. Instálala con:

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

**Ejemplo en 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/es/agent-browser/integracion-de-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.
