> 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/captcha-handling.md).

# Gestión de CAPTCHA

Aprende sobre los mecanismos de detección y gestión de CAPTCHA de Oxylabs Agent Browser y cómo usarlos.

{% hint style="warning" %}
`solve_captcha` El parámetro de manejo de CAPTCHA se está eliminando gradualmente. Para la solución recomendada actual, consulte [Manejador de páginas](https://developers.oxylabs.io/products/es/agent-browser/manejador-de-paginas.md).
{% endhint %}

Por defecto, Oxylabs Agent Browser no maneja CAPTCHAs automáticamente. Para habilitar la detección y el manejo automáticos tan pronto como se cargue una página, añada `solve_captcha=true` a la URL de conexión.

Si un sitio objetivo muestra desafíos de forma dinámica durante interacciones de varios pasos, o si necesita monitorización avanzada de eventos y optimizaciones de velocidad, puede usar los parámetros, eventos y técnicas documentados a continuación.

{% hint style="info" %}
**Nota:** Las tasas de éxito de acceso dependen mucho del objetivo. Los resultados pueden variar según la configuración específica del sitio objetivo, los niveles de aplicación (p. ej., seguimiento pasivo de huellas digitales frente a escalada activa del desafío) y la reputación en tiempo real de la IP residencial de la sesión.
{% endhint %}

## Monitorización de eventos de CAPTCHA

Puede monitorizar el ciclo de vida del solucionador. La extensión interna `oxylabs-runtime` del navegador emite eventos de estado directamente al `window` objeto. Al registrar un oyente de eventos "message" personalizado, su script puede rastrear estos eventos para pausar y reanudar acciones.

<table><thead><tr><th width="243">Tipo de evento</th><th>Descripción</th></tr></thead><tbody><tr><td><code>oxylabs-captcha-start</code></td><td>El solucionador ha detectado un CAPTCHA e inició el proceso de manejo.</td></tr><tr><td><code>oxylabs-captcha-end</code></td><td>El solucionador se completó correctamente y manejó el desafío.</td></tr><tr><td><code>oxylabs-captcha-solve-end</code></td><td>Evento alternativo de finalización emitido tras el éxito.</td></tr><tr><td><code>oxylabs-captcha-error</code></td><td>El solucionador no pudo manejar el desafío.</td></tr></tbody></table>

{% hint style="info" %}
La resolución automática es **deshabilitada por defecto**. Añada `solve_captcha=true` a la URL de conexión para habilitar el manejo automático y comenzar a emitir estos eventos.
{% endhint %}

### Ejemplos de código

Estos ejemplos muestran cómo inyectar un `init` script para capturar eventos de CAPTCHA en tiempo de ejecución antes de la navegación de la página, de modo que su script se pause durante el manejo activo.

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

```python
from playwright.sync_api import sync_playwright

username = "USERNAME_abc12"
password = "PASSWORD"
endpoint = "hb.oxylabs.io"
# solve_captcha=true enables handling and event emission (off by default)
browser_url = f"wss://{username}:{password}@{endpoint}?solve_captcha=true"

def run():
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(browser_url)
        ctx = browser.contexts[0]
        page = ctx.new_page()

        # Inject listener BEFORE navigation
        ctx.add_init_script("""
            window.addEventListener("message", (event) => {
                if (event.data && event.data.source === "oxylabs-runtime") {
                    window.__extensionStatus = event.data.type;
                }
            });
        """)

        page.goto("https://example.com/captcha-page", wait_until="domcontentloaded")

        # Wait for solver to complete (polls status flag)
        page.wait_for_function(
            """() => {
                const status = window.__extensionStatus;
                if (status === "oxylabs-captcha-error") {
                    throw new Error("CAPTCHA solving failed");
                }
                return status === "oxylabs-captcha-solve-end" || status === "oxylabs-captcha-end";
            }""",
            timeout=60000
        )
        print("CAPTCHA solved. Resuming automation...")
        browser.close()

if __name__ == "__main__":
    run()
```

{% endtab %}

{% tab title="JavaScript (Playwright)" %}

```javascript
import { chromium } from "playwright";

const username = "USERNAME_abc12";
const password = "PASSWORD";
const endpoint = "hb.oxylabs.io";
const browserUrl = `wss://${username}:${password}@${endpoint}?solve_captcha=true`;

(async () => {
    const browser = await chromium.connectOverCDP(browserUrl);
    const ctx = browser.contexts()[0];
    const page = await ctx.newPage();

    // Register init script to listen for oxylabs-runtime events
    await ctx.addInitScript(() => {
        window.addEventListener("message", (e) => {
            if (e.data?.source === "oxylabs-runtime") {
                window.__extensionStatus = e.data.type;
            }
        });
    });

    await page.goto("https://example.com/captcha-page", { waitUntil: "domcontentloaded" });

    try {
        // Halt script execution until CAPTCHA returns positive solve status
        await page.waitForFunction(() => {
            const status = window.__extensionStatus;
            if (status === "oxylabs-captcha-error") {
                throw new Error("CAPTCHA solving failed");
            }
            return status === "oxylabs-captcha-solve-end" || status === "oxylabs-captcha-end";
        }, null, { timeout: 60000 });

        console.log("CAPTCHA solved. Resuming automation...");
    } catch (err) {
        console.error("Error during bypass execution:", err.message);
    } finally {
        await browser.close();
    }
})();
```

{% endtab %}

{% tab title="JavaScript (Puppeteer)" %}

```javascript
import puppeteer from "puppeteer";

const username = "USERNAME_abc12";
const password = "PASSWORD";
const endpoint = "hb.oxylabs.io";
const browserUrl = `wss://${username}:${password}@${endpoint}?solve_captcha=true`;

(async () => {
    const browser = await puppeteer.connect({ browserWSEndpoint: browserUrl });
    const page = await browser.newPage();

    // Puppeteer alternative: Evaluate on document creation
    await page.evaluateOnNewDocument(() => {
        window.addEventListener("message", (e) => {
            if (e.data?.source === "oxylabs-runtime") {
                window.__extensionStatus = e.data.type;
            }
        });
    });

    await page.goto("https://example.com/captcha-page", { waitUntil: "domcontentloaded" });

    try {
        await page.waitForFunction(() => {
            const status = window.__extensionStatus;
            if (status === "oxylabs-captcha-error") {
                throw new Error("CAPTCHA solving failed");
            }
            return status === "oxylabs-captcha-solve-end" || status === "oxylabs-captcha-end";
        }, { timeout: 60000 });

        console.log("CAPTCHA solved. Resuming automation...");
    } catch (err) {
        console.error("Error during bypass execution:", err.message);
    } finally {
        await browser.close();
    }
})();
```

{% endtab %}
{% endtabs %}

## Disparadores manuales dinámicos

Algunos destinos solo muestran desafíos CAPTCHA después de acciones del usuario (p. ej., después de hacer clic en un botón interactivo de envío de formulario o de realizar desplazamiento dinámico).

Puede activar programáticamente el controlador de CAPTCHA de Agent Browser en cualquier momento de su sesión usando `el evento` directamente al objeto window:

```
window.postMessage({ action: "solve_captcha", type: "type_name" }, "*");
```

{% hint style="info" %}
Para obtener más información sobre los tipos de CAPTCHA compatibles, contacte con el soporte de Oxylabs ([chat en vivo](https://oxylabs.io/) o [correo electrónico](mailto:support@oxylabs.io)) o con tu gerente de cuenta dedicado.
{% endhint %}

### Patrón estándar de activación

Para elementos típicos, active el solucionador inmediatamente después de ejecutar la acción del usuario:

```javascript
// Perform form interaction
await page.click("#form-submit-button");

// Trigger solving for late-stage CAPTCHA
await page.evaluate(() => {
    window.postMessage({ action: "solve_captcha", type: "type_name" }, "*");
});
```

{% hint style="info" %}
Para obtener más información sobre los tipos de CAPTCHA compatibles o excepciones para tipos específicos, contacte con el soporte de Oxylabs (chat en vivo o correo electrónico) o con su Gerente de Cuenta Dedicado para obtener más detalles.
{% endhint %}

## Optimización de velocidad

El manejo de CAPTCHAs añade latencia de ejecución mecánica. Cuando haga scraping de destinos que imponen puertas CAPTCHA repetitivas, considere estos métodos para mejorar el rendimiento:

<table data-header-hidden><thead><tr><th width="175"></th><th></th></tr></thead><tbody><tr><td><strong>Reutilizar sesiones</strong></td><td>Una vez que una sesión de navegador remoto completa un CAPTCHA en un dominio, la verificación se guarda. Navegue repetidamente o realice pasos adicionales de la página dentro de la misma sesión del navegador sin reactivar las rutinas de resolución de desafíos.</td></tr><tr><td><strong>Multipestaña</strong></td><td>En lugar de conexiones WebSocket separadas (que inician sandboxes distintos con pools de cookies vacíos), ejecute tareas concurrentes abriendo varias pestañas o contextos dentro de su sesión existente, para reducir el tiempo de conexión y verificación en todas las páginas.</td></tr><tr><td><strong>Activar de forma selectiva</strong></td><td>Dado que <code>solve_captcha</code> está desactivado por defecto, actívelo solo (<code>solve_captcha=true</code>) para las conexiones específicas que lo necesiten, en lugar de dejarlo activado para todo un flujo de trabajo — esto evita la latencia de inicialización del solucionador en páginas o sesiones que no enfrentan desafíos CAPTCHA.</td></tr></tbody></table>


---

# 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/captcha-handling.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.
