# Bencina en Línea Chile - CNE Fuel Prices API (`scraperschile/bencina-en-linea`) Actor

Consulta precios oficiales de combustibles y estaciones de servicio de Chile mediante la API autenticada de la Comisión Nacional de Energía. Filtra por región, comuna, marca, combustible, antigüedad y precio.

- **URL**: https://apify.com/scraperschile/bencina-en-linea.md
- **Developed by:** [Scrapers Chile](https://apify.com/scraperschile) (community)
- **Categories:** Automation, Lead generation, Other
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Bencina en Línea Chile - API de precios de combustible CNE

Consulta estaciones de servicio y precios oficiales de combustibles en Chile. El Actor transforma la respuesta de la API de la Comisión Nacional de Energía (CNE) en registros listos para descargar como JSON, CSV, Excel o consumir mediante API.

Busca gasolina 93, 95 y 97, diésel, kerosene, GNC y GLP por región, comuna, marca, precio y fecha de actualización. Es útil para comparar precios, analizar cobertura de estaciones, vigilar cambios y construir aplicaciones de movilidad o inteligencia de mercado.

### Importante antes de publicar

Este Actor permanece **privado mientras se aclaran las condiciones comerciales de la API**. La [API CNE](https://api.cne.cl/) anuncia acceso completo y gratuito para conectar aplicaciones, y su [documentación oficial](https://apidocs.cne.cl/lista-estaciones-de-servicio-22976905e0) identifica `GET /api/v4/estaciones` como un recurso protegido con token Bearer. Además, la [Resolución Exenta CNE N°492-2023](https://www.cne.cl/wp-content/uploads/2023/10/Rex-CNE-N-492-2023_BEL-2.0.pdf) señala que los precios de combustibles al público tienen carácter de información pública.

La política del portal ciudadano Bencina en Línea, en cambio, limita la información visible del sitio a fines particulares y no comerciales. Este Actor no extrae ese portal: utiliza exclusivamente `api.cne.cl` con el token propio de cada usuario. Como la documentación de la API no publica una licencia comercial inequívoca, antes de monetizarlo conviene obtener confirmación escrita de CNE y exigir a cada usuario cumplir sus condiciones. Contacto publicado: `soporteapi@cne.cl`.

### Requisito: tu token CNE

1. Regístrate en [api.cne.cl](https://api.cne.cl/).
2. Obtén tu token personal.
3. Pégalo en `cneApiToken` como campo secreto.

El campo usa la protección `isSecret` de Apify: la plataforma lo cifra antes de guardarlo en la entrada del run y solo lo descifra dentro de la ejecución. El Actor lo envía exclusivamente en el encabezado `Authorization` de la consulta oficial; no lo escribe en resultados, `OUTPUT`, dataset ni logs.

### Datos entregados

- Identificador, marca, dirección, comuna y región de la estación.
- Coordenadas cuando la API las informa.
- Combustible, tipo de atención, precio y unidad.
- Fecha de actualización y estado de mantenimiento.
- Servicios declarados por la estación.
- Enlace a Bencina en Línea y fecha de extracción.

Cada registro corresponde a una combinación única de estación, combustible y tipo de atención.

### Filtros disponibles

- Región y comuna.
- Marca o distribuidor.
- Uno o varios combustibles.
- Antigüedad máxima del precio.
- Inclusión de estaciones en mantenimiento.
- Orden por precio, actualización o ubicación.
- Límite de resultados para controlar tiempo y costo.

### Ejemplo de entrada

```json
{
  "cneApiToken": "TU_TOKEN_CNE",
  "region": "Metropolitana de Santiago",
  "commune": "Providencia",
  "fuelTypes": ["93", "Diesel"],
  "maxPriceAgeDays": 30,
  "sortBy": "price_asc",
  "maxResults": 100
}
```

### Ejemplo de resultado

```json
{
  "station_id": "100",
  "brand": "COPEC",
  "address": "Av. Ejemplo 123",
  "commune": "Providencia",
  "region": "Metropolitana de Santiago",
  "fuel_name": "Gasolina 93",
  "attention_type": "Asistido",
  "price": 1290,
  "unit": "CLP/L",
  "in_maintenance": false,
  "source": "Comisión Nacional de Energía - Bencina en Línea"
}
```

### Precio

El archivo de eventos incluye `apify-actor-start` y `result` con precio cero únicamente como marcadores. El precio definitivo debe configurarse después de obtener permiso de CNE y medir varias ejecuciones reales en Apify. Apify informa que la utilidad PPE se calcula como `0,8 × ingresos − costos de plataforma`, por lo que un margen neto de 99,5% no es matemáticamente alcanzable bajo la comisión actual.

### Calidad y límites

- Fuente: Comisión Nacional de Energía.
- La CNE y las estaciones son responsables de la vigencia de los valores publicados.
- Un token inválido se rechaza inmediatamente y nunca se reintenta ni se muestra.
- Los errores transitorios de red sí se reintentan de forma acotada.
- El Actor no consulta el portal ciudadano ni reutiliza credenciales de terceros.

# Actor input Schema

## `cneApiToken` (type: `string`):

Token Bearer personal obtenido en https://api.cne.cl/. Apify lo almacena cifrado como entrada secreta y no aparece en resultados ni logs.

## `region` (type: `string`):

Nombre o código de región. Vacío busca en todo Chile.

## `commune` (type: `string`):

Nombre de comuna. Vacío incluye todas las comunas de la región.

## `brand` (type: `string`):

Filtro opcional, por ejemplo COPEC, SHELL o ARAMCO.

## `fuelTypes` (type: `array`):

Uno o más combustibles. Una lista vacía incluye todos.

## `maxPriceAgeDays` (type: `integer`):

Descarta precios con más días de antigüedad. Usa 0 para no filtrar.

## `includeMaintenance` (type: `boolean`):

Incluye estaciones marcadas como en mantenimiento por la fuente.

## `sortBy` (type: `string`):

Ordena por precio, fecha de actualización o ubicación.

## `maxResults` (type: `integer`):

Cada resultado corresponde a una combinación estación-combustible-atención.

## `timeoutSecs` (type: `integer`):

Segundos máximos para esperar la API CNE.

## `retries` (type: `integer`):

Intentos ante errores transitorios de red o servidor.

## Actor input object example

```json
{
  "region": "Metropolitana de Santiago",
  "commune": "Providencia",
  "fuelTypes": [
    "93"
  ],
  "maxPriceAgeDays": 30,
  "includeMaintenance": false,
  "sortBy": "price_asc",
  "maxResults": 500,
  "timeoutSecs": 30,
  "retries": 3
}
```

# Actor output Schema

## `status` (type: `string`):

No description

## `records` (type: `string`):

No description

## `source` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("scraperschile/bencina-en-linea").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("scraperschile/bencina-en-linea").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call scraperschile/bencina-en-linea --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,scraperschile/bencina-en-linea"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/bxrxGOPqrXA1ZAiYo/builds/C7JDKHgtxiHhI8pwQ/openapi.json
