> 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/captcha-handling.md). Agents can also search and read this documentation through its [MCP server](https://developers.oxylabs.io/~gitbook/mcp).

# Tratamento de CAPTCHA

Saiba mais sobre os mecanismos de detecção e tratamento de CAPTCHA do Agent Browser da Oxylabs e como usá-los.

{% hint style="warning" %}
`solve_captcha` O parâmetro de tratamento de CAPTCHA está sendo descontinuado. Para a solução recomendada atual, veja [Gerenciador de páginas](https://developers.oxylabs.io/products/pt-br/agent-browser/tratamento-de-paginas.md).
{% endhint %}

Por padrão, o Oxylabs Agent Browser não trata CAPTCHAs automaticamente. Para habilitar a detecção e o tratamento automáticos assim que uma página carregar, adicione `solve_captcha=true` à sua URL de conexão.

Se um site-alvo exibir desafios dinamicamente durante interações em várias etapas, ou se você precisar de monitoramento avançado de eventos e otimizações de velocidade, você pode usar os parâmetros, eventos e técnicas documentados abaixo.

{% hint style="info" %}
**Observação:** As taxas de sucesso de acesso dependem muito do alvo. Os resultados podem variar com base na configuração específica do site de destino, nos níveis de aplicação (por exemplo, rastreamento passivo de fingerprint versus escalonamento ativo de desafio) e na reputação em tempo real do IP residencial da sessão.
{% endhint %}

## Monitoramento de eventos de CAPTCHA

Você pode monitorar o ciclo de vida do resolvedor. A extensão interna `oxylabs-runtime` extensão do navegador transmite eventos de status diretamente para o `window` object. Ao registrar um listener personalizado de evento "message", seu script pode rastrear esses eventos para pausar e retomar ações.

<table><thead><tr><th width="243">Tipo de evento</th><th>Descrição</th></tr></thead><tbody><tr><td><code>oxylabs-captcha-start</code></td><td>O resolvedor detectou um CAPTCHA e iniciou o processo de tratamento.</td></tr><tr><td><code>oxylabs-captcha-end</code></td><td>O resolvedor concluiu com sucesso e tratou o desafio.</td></tr><tr><td><code>oxylabs-captcha-solve-end</code></td><td>Evento alternativo de conclusão emitido após o sucesso.</td></tr><tr><td><code>oxylabs-captcha-error</code></td><td>O resolvedor falhou ao tratar o desafio.</td></tr></tbody></table>

{% hint style="info" %}
A resolução automática está **desativada por padrão**. Adicione `solve_captcha=true` à sua URL de conexão para habilitar o tratamento automático e começar a emitir esses eventos.
{% endhint %}

### Exemplos de código

Esses exemplos mostram como injetar um `init` script para capturar eventos de CAPTCHA em tempo de execução antes da navegação da página, para que seu script pause durante o tratamento ativo.

{% 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 %}

## Acionadores manuais dinâmicos

Alguns alvos só exibem desafios CAPTCHA após ações do usuário (por exemplo, após clicar em um botão interativo de envio de formulário ou realizar rolagem dinâmica).

Você pode acionar o manipulador de CAPTCHA do Agent Browser programaticamente a qualquer momento na sua sessão usando `window.postMessage` evento diretamente para o objeto window:

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

{% hint style="info" %}
Para saber mais sobre os tipos de CAPTCHA suportados, entre em contato com o suporte da Oxylabs ([chat ao vivo](https://oxylabs.io/) or [e-mail](mailto:support@oxylabs.io)) ou com seu Gerente de Conta Dedicado.
{% endhint %}

### Padrão de acionamento convencional

Para elementos típicos, acione o resolvedor imediatamente após executar a ação do usuário:

```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 saber mais sobre os tipos de CAPTCHA suportados ou exceções para tipos específicos, entre em contato com o suporte da Oxylabs (chat ao vivo ou e-mail) ou com seu Gerente de Conta Dedicado para mais detalhes.
{% endhint %}

## Otimização de velocidade

O tratamento de CAPTCHAs adiciona latência de execução mecânica. Ao fazer scraping de alvos que impõem etapas repetitivas de CAPTCHA, considere estes métodos para melhor desempenho:

<table data-header-hidden><thead><tr><th width="175"></th><th></th></tr></thead><tbody><tr><td><strong>Reutilização de sessões</strong></td><td>Depois que uma sessão remota do navegador completa um CAPTCHA em um domínio, a verificação é salva. Navegue repetidamente ou execute etapas adicionais da página dentro da mesma sessão do navegador sem disparar novamente rotinas de resolução de desafios.</td></tr><tr><td><strong>Múltiplas abas</strong></td><td>Em vez de conexões WebSocket separadas (que iniciam sandboxes distintas com pools de cookie vazios), execute tarefas concorrentes abrindo várias abas ou contextos dentro da sua sessão existente, para reduzir o tempo de conexão e verificação em todas as páginas.</td></tr><tr><td><strong>Habilitar seletivamente</strong></td><td>Como <code>solve_captcha</code> está desativado por padrão, habilite-o apenas (<code>solve_captcha=true</code>)</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/pt-br/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.
