# INE España: Estadísticas Oficiales & Series Temporales (`datacraft_studio/ine-spain-scraper`) Actor

Scraper y API del INE (Instituto Nacional de Estadística de España). Extrae IPC, Inflación, Empleo/EPA, Precios Vivienda (IPV), Hipotecas, Población, PIB y series temporales normalizadas.

- **URL**: https://apify.com/datacraft\_studio/ine-spain-scraper.md
- **Developed by:** [DataCraft Studio](https://apify.com/datacraft_studio) (community)
- **Categories:** Real estate, Automation, AI
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.40 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## 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

## 📊 INE España Scraper: Estadísticas Oficiales, Series Temporales e Indicadores Económicos

> **Extrae, normaliza y automatiza datos del Instituto Nacional de Estadística (INE de España): IPC, Inflación, Empleo/EPA, Vivienda (IPV), Hipotecas, Población/Padrón, PIB, Salarios y más de 112 operaciones oficiales en formato JSON/CSV listo para producción.**

[![Apify Actor](https://img.shields.io/badge/Apify-Actor-orange?style=flat-square\&logo=apify)](https://apify.com)
[![Data Quality](https://img.shields.io/badge/Data%20Quality-B2B%20Standard-emerald?style=flat-square)](https://apify.com)
[![Pricing](https://img.shields.io/badge/Pricing-%242.40%20%2F%201K%20items-blue?style=flat-square)](https://apify.com)
[![Compliance](https://img.shields.io/badge/Compliance-Open%20Data%20%2F%20GDPR-green?style=flat-square)](https://apify.com)

***

### 🎯 1. ¿Por qué este Actor? (Value Proposition)

El **Instituto Nacional de Estadística (INE)** es la principal fuente de verdad socioeconómica y demográfica de España. Sin embargo, acceder a sus datos mediante métodos tradicionales presenta graves fricciones:

- La navegación web por INEbase es manual, lenta y compleja.
- La API cruda Tempus3 devuelve estructuras anidadas difíciles de interpretar, códigos numéricos crípticos y formatos de fechas variables.
- Falta de normalización automática de dimensiones territoriales, unidades y valores numéricos.

Este Actor resuelve estos problemas convirtiéndose en la **interfaz definitiva y universal de datos del INE**:

- ✅ **1-Click Presets**: Indicadores clave listos para consumir (IPC, Inflación, Empleo EPA, Hipotecas, Precios Vivienda IPV, PIB, Población, Salarios).
- ✅ **Búsqueda Inteligente**: Descubre tablas y operaciones entre las más de 112 estadísticas oficiales por palabras clave (`alquiler`, `hoteles`, `turismo`, `defunciones`, `vehículos`).
- ✅ **Datos B2B 100% Limpios**: Importes como `float` puro, fechas en estándar `ISO 8601`, desgloses categóricos y ámbito territorial identificados.
- ✅ **Listo para LLMs & RAG**: Salida perfectamente formateada para alimentar asistentes de IA, agentes MCP y pipelines de análisis macroeconómico.

***

### 🚀 2. Características Diferenciales y Tabla Comparativa

| Característica | 🛠️ Extracción Manual / API Cruda INE | ⚡ Otros Scrapers Genéricos | 🏆 **INE España Scraper (Este Actor)** |
| :--- | :--- | :--- | :--- |
| **Facilidad de Uso** | Requiere programar clientes HTTP complejos y mapear IDs | Configuración rígida de pocas tablas | **1-Click Presets + Búsqueda por texto + Códigos libres** |
| **Normalización Numérica** | Cadenas con comas (`"102,4"`) o secretos estadísticos | Texto plano sin tipar | **Valores `float` puros procesados y saneados** |
| **Estandarización de Fechas** | Timestamps en milisegundos o formatos `aaaammdd` | Inconsistente | **ISO 8601 (`YYYY-MM-DDTHH:MM:SSZ`) universal** |
| **Desglose de Variables** | Arrays numéricos `MetaData` anidados | Información perdida o truncada | **Mapeo clave-valor completo de dimensiones** |
| **Identificación Territorial** | Códigos numéricos de provincia/CCAA | No resuelto | **Columna territorial directa (Nacional, CCAA, Provincias)** |
| **Inventario de Operaciones** | PDF / Búsqueda manual en la web | No disponible | **Modo Catálogo de 112+ operaciones en 1 clic** |
| **Integración con IA / MCP** | Requiere transformaciones complejas | No optimizado | **Esquema estructurado listo para GPT-4, Claude y n8n** |

***

### 💼 3. Casos de Uso Empresariales (B2B)

#### 🏢 1. Real Estate & Proptech

- Monitoriza la evolución del **Índice de Precios de Vivienda (IPV)** y de **Compraventas de Inmuebles (ETDP)** por Comunidad Autónoma.
- Cruza datos de **Hipotecas constituidas** e importes medios prestados para análisis de riesgo crediticio y tasaciones.

#### 📈 2. Análisis Financiero & Macroeconomía

- Automatiza la ingesta mensual del **IPC (Índice de Precios de Consumo)** general y subyacente para indexación de contratos, nóminas y cláusulas de revisión de precios.
- Modela previsiones de crecimiento con la **Contabilidad Nacional Trimestral (PIB)** y la **Encuesta de Población Activa (EPA)**.

#### 🤖 3. RAG, Agentes de IA y Contexto Empresarial (MCP)

- Conecta este Actor a agentes de IA mediante el **Apify Model Context Protocol (MCP)** para responder preguntas en tiempo real sobre estadísticas oficiales españolas.

#### 🏨 4. Turismo & Sector Servicios

- Monitorea flujos turísticos con la **Encuesta de Ocupación Hotelera (EOH)** y el gasto medio por turista para optimizar precios y estacionalidad.

***

### 💰 4. Transparencia de Consumo y Costes

El Actor utiliza el modelo **Pay Per Event (Pago por Resultado)** en Apify Store:

| Métrica | Coste Estimado |
| :--- | :--- |
| **Tarifa por Registro (Default Dataset Item)** | **$2.40 / 1,000 registros** ($0.0024 por dato extraído) |
| **Tarifa de Inicio de Ejecución (Actor Start)** | **$0.00005** |
| **Consumo de Compute Units (CUs)** | Optimizado con peticiones HTTP asíncronas de bajo consumo (~0.002 CUs por ejecución) |

> 💡 **Ejemplo Práctico:** Extraer los últimos 12 meses de IPC general y subyacente para todas las Comunidades Autónomas (~200 registros) cuesta **menos de $0.0005 USD**.

***

### ⚙️ 5. Guía de Parámetros de Entrada (Input)

| Campo | Tipo | Requerido | Default | Descripción |
| :--- | :--- | :---: | :--- | :--- |
| `mode` | `String (Select)` | **Sí** | `PRESET` | Modo de extracción: `PRESET`, `SEARCH`, `CUSTOM_OPERATION`, `CUSTOM_TABLE`, `DIRECT_URLS`, `OPERATIONS_CATALOG`. |
| `presetOperation` | `String (Select)` | No | `IPC` | Indicador preconfigurado (`IPC`, `EPA`, `IPV`, `HIPOTECAS`, `PADRON`, `PIB`, `TRANSMISIONES`, `TURISMO`, `SALARIOS`, `EMPRESAS`). |
| `searchQuery` | `String` | No | `"alquiler"` | Texto de búsqueda en el catálogo de operaciones del INE. |
| `operationCode` | `String` | No | `"IPC"` | Código oficial Tempus3 (ej. `IPC`, `IPV`, `EPA`, `ETDP`). |
| `tableId` | `String` | No | `"24077"` | Identificador numérico de tabla estadística del INE. |
| `directUrls` | `Array[String]` | No | `[]` | Lista de enlaces directos de tablas de ine.es. |
| `periodsCount` | `Integer` | No | `12` | Últimos periodos cronológicos por serie (0 = todo el histórico). |
| `dateFrom` | `String` | No | `null` | Fecha inicial en formato `YYYY-MM-DD`. |
| `dateTo` | `String` | No | `null` | Fecha final en formato `YYYY-MM-DD`. |
| `maxTables` | `Integer` | No | `5` | Límite de tablas estadísticas a procesar por operación. |
| `maxItems` | `Integer` | No | `1000` | Límite máximo de observaciones a guardar en el dataset. |
| `proxyConfiguration` | `Object` | No | `{"useApifyProxy": false}` | Configuración opcional de Proxies Apify. |

#### 📋 Ejemplo de Input en JSON

```json
{
  "mode": "PRESET",
  "presetOperation": "IPC",
  "periodsCount": 12,
  "maxTables": 3,
  "maxItems": 500,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

***

### 📊 6. Ejemplo de Salida Estructurada (Dataset Output)

Cada registro en el dataset representa una observación estadística normalizada con sus metadatos y dimensiones:

```json
{
  "operation_code": "IPC",
  "operation_name": "Índice de Precios de Consumo (Inflación)",
  "table_id": "24077",
  "table_name": "Índice general nacional. Series desde enero de 1961",
  "series_code": "IPC290751",
  "series_name": "Nacional. Índice general. Índice.",
  "date": "2026-07-01T00:00:00+00:00",
  "year": 2026,
  "period": "Mes 07",
  "value": 103.899,
  "unit": "Índice",
  "scale": "Unidades",
  "territory": "Nacional",
  "variable_breakdown": {
    "Totales Territoriales": "Nacional",
    "Grupos ECOICOP": "Índice general",
    "Índices y Tasas": "Índice"
  },
  "source_url": "https://www.ine.es/jaxiT3/Tabla.htm?t=24077",
  "extracted_at": "2026-08-23T11:05:30.123456+00:00"
}
```

***

### 🔗 7. Automatización e Integraciones

#### 🐍 Python (Apify Client SDK)

```python
from apify_client import ApifyClient

client = ApifyClient("TU_API_TOKEN")

run_input = {
    "mode": "PRESET",
    "presetOperation": "IPV",
    "periodsCount": 8,
    "maxItems": 200,
}

run = client.actor("USUARIO/ine-spain-scraper").call(run_input=run_input)

## Iterar sobre los datos normalizados
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(f"[{item['date']}] {item['territory']} - {item['series_name']}: {item['value']} {item.get('unit')}")
```

#### 🟩 Node.js / JavaScript

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

const client = new ApifyClient({ token: 'TU_API_TOKEN' });

const input = {
    mode: 'PRESET',
    presetOperation: 'EPA',
    periodsCount: 4,
};

const run = await client.actor('USUARIO/ine-spain-scraper').call(input);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(`Extraídos ${items.length} registros oficiales del INE.`);
```

#### ⚡ Make.com / Zapier / n8n

1. Añade el módulo de **Apify: Run Actor**.
2. Selecciona `ine-spain-scraper` y define el JSON de configuración.
3. Conecta el trigger de salida a **Google Sheets**, **Notion**, **PostgreSQL** o tu **Data Warehouse**.

***

### ❓ 8. Preguntas Frecuentes (FAQ) y Cumplimiento Legal

##### ¿Se necesita API Key o registro en el INE?

No. El Instituto Nacional de Estadística (INE) ofrece sus datos bajo la política de datos abiertos del Gobierno de España (*Open Data / Reutilización de Información del Sector Público*). Este Actor interactúa de forma eficiente y respetuosa con los servicios públicos sin requerir credenciales adicionales.

##### ¿Los datos están actualizados?

Sí. El Actor consulta en tiempo real los servidores oficiales del INE, por lo que cualquier nota de prensa o publicación estadística recién emitida estará disponible de inmediato.

##### ¿Puedo extraer series históricas completas?

Sí. Puedes configurar `periodsCount: 0` para extraer la totalidad de observaciones disponibles desde el inicio de la serie histórica (en algunas series, desde 1961).

***

### 🌐 9. English Summary (Global Apify Store Overview)

#### Overview

**INE Spain Official Statistics Scraper** is the premier data extractor for Spain's National Statistics Institute (**Instituto Nacional de Estadística - INE**). It provides automated, normalized access to official macroeconomic, demographic, and real estate data.

#### Key Features

- **1-Click Presets**: Immediate extraction of CPI/Inflation (IPC), Unemployment & Employment (EPA), Housing Price Index (IPV), Mortgages (HPT), GDP (PIB), Population/Census, and Tourism.
- **Smart Keyword Search**: Explore and extract from more than 112 official statistical operations.
- **B2B-Ready Clean Data**: Clean `float` numbers, ISO 8601 timestamps, complete categorical breakdowns, and territorial segmentation.
- **AI & RAG Optimized**: Ready to integrate with LLMs, Claude/GPT assistants via Apify Model Context Protocol (MCP), and ETL workflows in Make, Zapier, or n8n.

# Actor input Schema

## `mode` (type: `string`):

Selecciona cómo deseas obtener los datos del INE: por presets de alto impacto, búsqueda semántica, código de operación/tabla o catálogo.

## `presetOperation` (type: `string`):

Elige el indicador económico o demográfico clave que deseas extraer.

## `searchQuery` (type: `string`):

Términos de búsqueda para descubrir operaciones y tablas estadísticas (ej: 'alquiler', 'vehículos', 'natalidad', 'comercio', 'hoteles').

## `operationCode` (type: `string`):

Código alfanumérico oficial de la operación en INE (ej: 'IPC', 'IPV', 'EPA', 'ETDP', 'EI', 'ICLA').

## `tableId` (type: `string`):

Identificador numérico de tabla estadística del INE (ej: 24077 para IPC general, 50902 para precios de vivienda).

## `directUrls` (type: `array`):

Lista de enlaces de tablas o datos de ine.es (ej: https://www.ine.es/jaxiT3/Tabla.htm?t=50902).

## `periodsCount` (type: `integer`):

Cantidad de últimos periodos cronológicos a extraer para cada serie (ej: 12 para el último año mensual, 4 para últimos 4 trimestres, 0 para todo el histórico).

## `dateFrom` (type: `string`):

Filtrar observaciones a partir de esta fecha en formato YYYY-MM-DD (ej: 2023-01-01).

## `dateTo` (type: `string`):

Filtrar observaciones hasta esta fecha en formato YYYY-MM-DD (ej: 2026-12-31).

## `maxTables` (type: `integer`):

Límite de tablas estadísticas a procesar por operación para evitar consumos desmedidos en operaciones gigantescas.

## `maxItems` (type: `integer`):

Número máximo de observaciones a guardar en el dataset (0 para sin límite).

## `proxyConfiguration` (type: `object`):

Configuración de Proxies de Apify para rotación de IPs y máxima estabilidad.

## Actor input object example

```json
{
  "mode": "PRESET",
  "presetOperation": "IPC",
  "searchQuery": "alquiler",
  "operationCode": "IPC",
  "tableId": "24077",
  "directUrls": [
    "https://www.ine.es/jaxiT3/Tabla.htm?t=24077"
  ],
  "periodsCount": 12,
  "maxTables": 5,
  "maxItems": 1000,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `ineDataset` (type: `string`):

Conjunto de datos estructurados con series temporales, variables y valores normalizados del INE.

# 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 = {
    "presetOperation": "IPC",
    "searchQuery": "alquiler",
    "operationCode": "IPC",
    "tableId": "24077",
    "directUrls": [
        "https://www.ine.es/jaxiT3/Tabla.htm?t=24077"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("datacraft_studio/ine-spain-scraper").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 = {
    "presetOperation": "IPC",
    "searchQuery": "alquiler",
    "operationCode": "IPC",
    "tableId": "24077",
    "directUrls": ["https://www.ine.es/jaxiT3/Tabla.htm?t=24077"],
}

# Run the Actor and wait for it to finish
run = client.actor("datacraft_studio/ine-spain-scraper").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 '{
  "presetOperation": "IPC",
  "searchQuery": "alquiler",
  "operationCode": "IPC",
  "tableId": "24077",
  "directUrls": [
    "https://www.ine.es/jaxiT3/Tabla.htm?t=24077"
  ]
}' |
apify call datacraft_studio/ine-spain-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,datacraft_studio/ine-spain-scraper"
        }
    }
}

```

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/5EHvJquQcVt3cP0TY/builds/5EWiEOq2A568TwEox/openapi.json
