> 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/web-unblocker/custom-browser-instructions/browser-instructions-beta.md).

# Instrucciones del navegador (Beta)

Con Web Unblocker, puedes definir instrucciones del navegador al crear un trabajo para un proceso de recopilación de datos fluido.

Cuando usas Custom Browser Instructions, puedes definir tus propias instrucciones específicas del navegador que se ejecutan al renderizar JavaScript.

{% hint style="success" %}
Generar **Instrucciones automáticas del navegador** en el [**Playground de Web Scraper API**](https://dashboard.oxylabs.io/?route=/api-playground) en el panel de Oxylabs. Configura acciones del navegador, pruébalas y exporta las instrucciones generadas en formato JSON.
{% endhint %}

## ¿Cómo usarlo?

Para usar instrucciones del navegador, proporciona un conjunto de `browser_instructions` al crear un trabajo.

Supongamos que quieres buscar el término `cajas de pizza` en un sitio web.

<figure><img src="https://2786356907-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBQ7Zf9paoN3FTeGcyfY1%2Fuploads%2Fgit-blob-f4d808b71a0a56ac417c6c71f46b5a53d1401f29%2Fbi_1.png?alt=media" alt=""><figcaption></figcaption></figure>

Un ejemplo de los parámetros del trabajo sería el siguiente:

{% code overflow="wrap" %}

```bash
curl -k -x https://unblock.oxylabs.io:60000 \
-U 'USERNAME:PASSWORD' \
'https://www.ebay.com' \
-H 'x-oxylabs-render: html' \
-H "x-oxylabs-browser-instructions: [{\"type\":\"input\",\"value\":\"pizza boxes\",\"selector\":{\"type\":\"xpath\",\"value\":\"\/\/input[@class='gh-tb ui-autocomplete-input']\"}},{\"type\":\"click\",\"selector\":{\"type\":\"xpath\",\"value\":\"\/\/input[@type='submit']\"}},{\"type\":\"wait\",\"wait_time_s\":5}]"
```

{% endcode %}

**Paso 1.** Debes proporcionar el `x-oxylabs-render: html` parámetro.

**Paso 2.** Las instrucciones del navegador deben describirse en el `x-oxylabs-browser_instructions` campo.

{% hint style="info" %}
Las instrucciones del navegador proporcionadas como valor del encabezado deben escaparse en JSON y no contener espacios extra.
{% endhint %}

Las instrucciones de navegador de ejemplo anteriores especifican que el objetivo es introducir un término de búsqueda `cajas de pizza` en un campo de búsqueda, hacer clic en `search` el botón y esperar 5 segundos a que el contenido se cargue.

El resultado extraído debería verse así:

```html
<!doctype html><html>
Contenido después de ejecutar las instrucciones      
</html>
```

El HTML extraído debería verse así:

<figure><img src="https://2786356907-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBQ7Zf9paoN3FTeGcyfY1%2Fuploads%2Fgit-blob-15c3241746723aefc211766dbf8c4cb5549114ff%2Fbi_2.png?alt=media" alt=""><figcaption></figcaption></figure>

## Obtención de recursos del navegador <a href="#fetching-browser-resources" id="fetching-browser-resources"></a>

Proporcionamos una instrucción independiente del navegador para obtener recursos del navegador.

La función se define aquí:

Usando `fetch_resource` hará que el trabajo devuelva la primera aparición de un recurso Fetch/XHR que coincida con el formato proporcionado, en lugar del HTML que se está solicitando.

Supongamos que queremos apuntar a un recurso GraphQL que se obtiene al visitar de forma orgánica una página de producto en el navegador. Proporcionaremos la información del trabajo así:

{% code overflow="wrap" %}

```bash
curl -k -x https://unblock.oxylabs.io:60000 \
-U 'USERNAME:PASSWORD' \
'https://www.example.com/product-page/123' \
-H 'x-oxylabs-render: html' \
-H "x-oxylabs-browser-instructions: [{\"type\": \"fetch_resource\",\"filter\": \"\/graphql\/product-info\/123\"}]"
```

{% endcode %}

Estas instrucciones darán como resultado algo como esto:

```html
{"product_id": 123, "description": "", "price": 456}
```

## Lista de instrucciones del navegador compatibles <a href="#list-of-supported-browser-instructions" id="list-of-supported-browser-instructions"></a>

### Argumentos generales

Todas las instrucciones definidas a continuación tienen un conjunto coherente de argumentos. Los argumentos son los siguientes.

#### `type` <a href="#type" id="type"></a>

* **Tipo**: `Enum["click", "input", "scroll", "scroll_to_bottom", "wait", "wait_for_element", "fetch_resource"]`
* **Descripción:** Tipo de instrucción del navegador.

#### `timeout_s` <a href="#timeout_s" id="timeout_s"></a>

* **Tipo**: `int`
* **Descripción:** Cuánto tiempo pasa hasta que la acción se omite si no se completa a tiempo.
* **Restricciones**: 0 < `timeout_s` <= 60
* **Valor predeterminado**: 5

#### `wait_time_s` <a href="#wait_time_s" id="wait_time_s"></a>

* **Tipo**: `int`
* **Descripción:** Cuánto esperar antes de ejecutar la siguiente acción.
* **Restricciones**: 0 < `wait_time_s` <= 60
* **Valor predeterminado**: 0

#### `on_error` <a href="#on_error" id="on_error"></a>

* **Tipo**: `Enum["error", "skip"]`
* **Descripción:** Indica qué hacer con las instrucciones en caso de que esta instrucción falle:
  * `"error"`: Detiene la ejecución de las instrucciones del navegador.
  * `"skip"`: Continúa con la siguiente instrucción.
* **Valor predeterminado**: `"error"`

#### Ejemplo con argumentos generales

{% code overflow="wrap" %}

```bash
{\"type\": \"wait_for_element\", \"selector\": {\"type\": \"text\", \"value\": \"Load More Items\"},\"timeout_s\": 5, \"wait_time_s\": 2, \"on_error\": \"skip\"}
```

{% endcode %}

### Instrucciones <a href="#click" id="click"></a>

#### `click` <a href="#click" id="click"></a>

* **Descripción**: Hace clic en un elemento y espera un número determinado de segundos.
* **Argumentos:**
  * `type: str = "click"`
  * `selector: dict`
    * `type: Enum["xpath", "css", "text"]`
    * `value: str`
* **Ejemplo**:

{% code overflow="wrap" %}

```bash
{\"type\": \"click\",\"selector\": {\"type\": \"xpath\",\"value\": \"\/\/button\"}}
```

{% endcode %}

#### `input` <a href="#input" id="input"></a>

* **Descripción**: Introduce texto en un elemento seleccionado.
* **Argumentos:**
  * `type: str = "input"`
  * `selector: dict`
    * `type: Enum["xpath", "css", "text"]`
    * `value: str`
  * `value: str`
  * **Ejemplo:**

{% code overflow="wrap" %}

```bash
{\"type\": \"input\",\"selector\": {\"type\": \"xpath\",\"value\": \"\/\/input\"},\"value\": \"pizza boxes\"}
```

{% endcode %}

#### `scroll` <a href="#scroll" id="scroll"></a>

* **Descripción**: Desplaza una cantidad determinada de píxeles.
* **Argumentos:**
  * `type: str = "scroll"`
  * `x: int`
  * `y: int`
* **Ejemplo:**

```bash
{\"type\": \"scroll\",\"x\": 0,\"y\": 100}
```

#### `scroll_to_bottom` <a href="#scroll_to_bottom" id="scroll_to_bottom"></a>

* **Descripción**: Desplaza hasta el final durante un número determinado de segundos.
* **Argumentos:**
  * `type: str = "scroll_to_bottom"`
* **Ejemplo**:

```bash
{\"type\": \"scroll_to_bottom\",\"timeout_s\": 10}
```

### `wait` <a href="#wait" id="wait"></a>

* **Descripción**: Espera un número determinado de segundos.
* **Argumentos:**
  * `type: str = "wait"`
* **Ejemplo**:

```bash
{\"type\": \"wait\",\"wait_time_s\": 2}
```

#### `wait_for_element` <a href="#wait_for_element" id="wait_for_element"></a>

* **Descripción**: Espera a que el elemento cargue durante un número determinado de segundos.
* **Argumentos:**
  * `type: str = "wait_for_element"`
  * `selector: dict`
    * `type: Enum["xpath", "css", "text"]`
    * `value: str`
  * **Ejemplo:**

{% code overflow="wrap" %}

```bash
{\"type\": \"wait_for_element\",\"selector\": {\"type\": \"text\",\"value\": \"Load More Items\"},\"timeout_s\": 5}
```

{% endcode %}

#### `fetch_resource` <a href="#fetch_resource" id="fetch_resource"></a>

{% hint style="warning" %}
La URL de almacenamiento `fetch_resource` instruction must be the final instruction in the browser instructions list; any subsequent instructions will not be executed.
{% endhint %}

* **Descripción**: Obtiene la primera aparición de un recurso Fetch/XHR que coincida con el patrón establecido.
* **Argumentos:**
  * `type: str = "fetch_resource"`
  * `filter: str(RegEx expression)`
  * `on_error: Enum["error", "skip"]`
* **Ejemplo:**

```bash
{\"type\": \"fetch_resource\",\"filter\": \"\/graphql\/item\/\"}
```

### Validación de las instrucciones

Cualquier inconsistencia respecto al formato de la instrucción dará lugar a un `400` código de estado y un mensaje de error correspondiente.

Por ejemplo, una carga útil como esta:

```bash
[{\"type\": \"unsupported-wait\",\"wait_time_s\": 5}]}]
```

Dará como resultado:

```json
{    
    "errors": {
        "message": "Tipo de acción no compatible `unsupported-wait`, elige entre 'click,fetch_resource,input,scroll,scroll_to_bottom,wait,wait_for_element'"
    }
}
```

## Códigos de estado <a href="#status-codes" id="status-codes"></a>

Consulta nuestros códigos de respuesta detallados [**aquí**](https://developers.oxylabs.io/products/es/web-unblocker/response-codes.md).


---

# 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/web-unblocker/custom-browser-instructions/browser-instructions-beta.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.
