# BOE.es Subastas: Spanish Property Auction & Foreclosure Scraper (`signalflow/spain-auction-scout`) Actor

🇪🇸 Scrape subastas inmobiliarias de BOE.es: valoración, cargas y ref. catastral. 🏠 Get official Spanish property auction data, court details & 50/70% bidding limits. Search foreclosures and judicial auctions across Spain. Extrae ejecuciones hipotecarias y subastas judiciales fácilmente.

- **URL**: https://apify.com/signalflow/spain-auction-scout.md
- **Developed by:** [SignalFlow](https://apify.com/signalflow) (community)
- **Categories:** Real estate, Automation
- **Security:** Limited permissions
- **Stats:** 96 total users, 6 monthly users, 100.0% runs succeeded, 2 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 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?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

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

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## 🇪🇸 España Subasta Scout (Subastas BOE)

Este Actor extrae datos del portal oficial **Subastas BOE**

### ⚙️ Setup local (desarrollo)

```bash
pip install -r requirements.txt
playwright install chromium   # o: playwright install chrome
apify run
```

Si Chromium falla (SIGSEGV), instala Chrome y el actor usará `channel="chrome"` automáticamente. (Boletín Oficial del Estado) para obtener información precisa y detallada sobre futuras subastas de bienes inmuebles y activos en España. Está diseñado para inversores inmobiliarios, analistas y "subasteros" que buscan oportunidades.

***

### 🚀 ¿Por qué usar este Scraper?

El sitio web oficial [subastas.boe.es](https://subastas.boe.es/) es potente pero difícil de seguir a gran escala. Requiere navegar por múltiples pestañas para cada subasta para obtener la imagen completa. Este Actor resuelve esto:

1. **Scraping Profundo Multi-Pestaña**: Navega automáticamente por las pestañas *General*, *Autoridad*, *Bienes* y *Pujas* para extraer detalles ocultos.
2. **Soporte Multi-Lote**: Detecta subastas con múltiples lotes (ej. "(2 lotes)") e itera por cada uno para extraer detalles financieros y de propiedad específicos.
3. **Documentos**: Por defecto incluye enlaces (`titulo`, `url`) a PDFs del BOE (`verDocumento.php`). Opcionalmente puede descargar los PDFs al **Key-Value Store** de Apify y devolver `file_key`, `file_url` y `download_status` (ver más abajo).
4. **Cálculos de Referencia**: Calcula automáticamente los valores del 70% y 50% del valor de subasta para una estrategia de puja rápida.

### 🎯 Casos de Uso

- **Análisis de Inversión**: Filtrar propiedades en *Madrid* o *Barcelona* con una *Puja Mínima* baja.
- **Investigación de Mercado**: Analizar tendencias de subastas en diferentes provincias.
- **Monitoreo de Activos**: Rastrear tipos específicos de activos (Vivienda, Garaje, Solar).

### 💰 Cálculos Inteligentes

Proporcionamos campos calculados para ayudarle a evaluar la oportunidad al instante:

- **Valor de Referencia (70%)**: El umbral a menudo utilizado para aprobaciones de adjudicación directa.
- **Valor de Referencia (50%)**: Un límite inferior crítico para estrategias de puja.

### 💡 Consejos para Inversores

- **Provincias**: Seleccione `Todas las provincias` para obtener subastas de toda España, o filtre por provincias específicas (ej. `Madrid`, `Valencia/València`).
- **Max Items**: Establezca `maxItems` en `0` para no limitar el número de resultados (todas las entradas).
- **Tipo de Bien**: Filtre por `Vivienda`, `Garaje`, `Solar`, etc.
- **Depósito**: Extraemos el depósito exacto requerido para participar.

#### 🔃 Ordenación y ejecuciones incrementales (nuevo)

Para capturar solo las subastas **nuevas** en ejecuciones programadas (diarias), ordene por identificador de forma descendente y limite los resultados:

- **`sortBy`**: `fecha_fin` (por defecto, igual que BOE: las que terminan antes primero), `identificador`, `estado` o `postura_minima`.
- **`sortOrder`**: `asc` (por defecto) o `desc`.
- **Patrón recomendado para uso incremental**: `sortBy: "identificador"` + `sortOrder: "desc"` + un `maxItems` bajo (ej. `30`) → devuelve **las subastas publicadas más recientemente primero** y se detiene pronto, en lugar de recorrer todo el conjunto abierto en cada ejecución.
- **Filtros por fecha (opcionales)**: `fechaInicioDesde` / `fechaInicioHasta` (fecha de inicio de la subasta) y `fechaFinDesde` / `fechaFinHasta` (fecha de fin). Acepta `YYYY-MM-DD` o `dd/mm/yyyy`.

> Los valores por defecto (`sortBy: "fecha_fin"`, `sortOrder: "asc"`) mantienen el comportamiento anterior: nada cambia para integraciones existentes salvo que active estas opciones.

#### 📄 Documentos PDF (opcional)

Por **defecto** (`downloadDocumentsToKvs` omitido o `false`) el comportamiento es solo enlaces; no cambia respecto a integraciones antiguas.

| Input | Comportamiento |
|--------|----------------|
| `downloadDocumentsToKvs`: **false** u omitido | Solo `titulo` y `url` por documento. |
| `downloadDocumentsToKvs`: **true** | Descarga cada PDF con la misma sesión del navegador, lo guarda en el Key-Value Store por defecto y añade `file_key`, `download_status`; en ejecuciones en **Apify** también `file_url` (API del almacén). |

Algunos PDFs del BOE exigen **sesión iniciada**. Para ellos puede subir un JSON de **Playwright storage state** (tras iniciar sesión en `subastas.boe.es`, exportar con `context.storage_state()`) al Key-Value Store del run y pasar **`playwrightStorageStateKvsKey`** con el nombre del registro (alternativa: **`playwrightStorageStateJson`** como texto). Las sesiones pueden caducar; si `download_status` es `not_pdf_maybe_login`, hay que renovar el estado.

### 📦 Ejemplo de Salida

El scraper proporciona un conjunto de datos JSON limpio y estructurado con claves en **Español**, listo para integración:

```json
{
  "identificador": "SUB-JA-2025-255845",
  "tipo_subasta": "JUDICIAL EN VÍA DE APREMIO",
  "fecha_inicio": "2025-12-30T18:00:00+01:00",
  "fecha_conclusion": "2026-01-19T18:00:00+01:00",
  "valor_subasta": 305348.0,
  "valor_referencia_70_porciento": 213743.6,
  "valor_referencia_50_porciento": 152674.0,
  "deposito": 15267.4,
  "puja_minima": 0.0,
  "cantidad_reclamada": 135353.97,
  "descripcion": "VIVIENDA en Calle Principal...",
  "descripcion_general": "Vivienda unifamiliar... descripción registral completa del bloque superior",
  "direccion": "C/ Mayor, 1",
  "localidad": "Madrid",
  "provincia": "Madrid",
  "autoridad_nombre": "JUZGADO 1 INSTANCIA 5",
  "autoridad_email": "juzgado5@justicia.es",
  "lotes_data": [
    {
      "nombre": "Lote 1",
      "financiero": { "valor_subasta": 210000.0 },
      "bien": { "descripcion": "VIVIENDA en...", "descripcion_general": "Descripción registral completa..." }
    }
  ],
  "documentos": [
    {
      "titulo": "Certificación de Cargas",
      "url": "https://subastas.boe.es/verDocumento.php?idSub=..."
    },
    {
      "titulo": "Edicto",
      "url": "https://subastas.boe.es/verDocumento.php?idSub=...",
      "file_key": "DOC_SUB-JA-2026-259951_0_Edicto.pdf",
      "file_url": "https://api.apify.com/v2/key-value-stores/STORE_ID/records/...",
      "download_status": "ok"
    }
  ],
  "detail_url": "https://subastas.boe.es/detalleSubasta.php?idSub=SUB-JA-...",
  "google_maps_url": "https://www.google.com/maps/search/?api=1&query=..."
}
```

> **`descripcion` vs `descripcion_general`**: `descripcion` toma el valor de la celda "Descripción" de la tabla *Datos del bien subastado*. Los juzgados a menudo rellenan esa celda con referencias inútiles ("LA ARRIBA SEÑALADA", vacía, etc.). `descripcion_general` extrae el bloque de texto que aparece **encima** de esa tabla (dentro de la pestaña *Bienes* o de cada *Lote*), donde suele estar la descripción registral completa y valiosa. El campo original `descripcion` no se modifica.

### 📜 Aviso Legal

Esta herramienta es solo para fines informativos. Verifique siempre los detalles de la subasta en el sitio web oficial del juzgado o autoridad gestora.

***

## 🇬🇧 Spain Auction Scout (Subastas BOE)

This Actor scrapes the official **Subastas BOE** (Boletín Oficial del Estado) portal to extract accurate, deep-level data on upcoming real estate and asset auctions in Spain. It is designed for real estate investors, analysts, and "subasteros" looking for opportunities.

### 🚀 Why use this Scraper?

The official [subastas.boe.es](https://subastas.boe.es/) website is incredibly powerful but difficult to monitor at scale. It requires navigating through multiple tabs for every single auction to get the full picture. This Actor solves that by:

1. **Multi-Tab Deep Scraping**: Automatically clicks through *General*, *Autoridad*, *Bienes*, and *Pujas* tabs to extract hidden details.
2. **Multi-Lot Support**: Detects auctions with multiple lots (e.g., "(2 lotes)") and iterates through each one to extract specific financial and property details.
3. **Documents**: By default outputs document links (`titulo`, `url`) to BOE PDFs (`verDocumento.php`). Optionally downloads PDFs into the default **Key-Value Store** and adds `file_key`, `file_url`, and `download_status` (see below).
4. **Reference Calculations**: Automatically calculates 70% and 50% values of the auction price for quick bidding strategy.

### 🎯 Use Cases

- **Investment Analysis**: Filter for properties in *Madrid* or *Barcelona* with a low *Puja Mínima*.
- **Market Research**: Analyze auction trends across different provinces.
- **Asset Monitoring**: Track specific types of assets (Vivienda, Garaje, Solar).

### 💰 Smart Calculations

We provide calculated fields to help you assess the opportunity instantly:

- **Valor de Referencia (70%)**: The threshold often used for direct award approvals.
- **Valor de Referencia (50%)**: A critical lower bound for bidding strategies.

### 💡 Tips for Investors

- **Provinces**: Select `Todas las provincias` (All provinces) to get auctions from all of Spain, or filter by specific provinces (e.g., `Madrid`, `Valencia/València`).
- **Max Items**: Set `maxItems` to `0` for no limit (all entries).
- **Property Type**: Filter by `Vivienda` (Housing), `Garaje`, `Solar`, etc.
- **Deposit (Depósito)**: We extract the exact deposit required to participate.

#### 📄 PDF documents (optional)

**Default** (`downloadDocumentsToKvs` omitted or `false`): only `titulo` and `url` per document — same as before for existing clients.

| Input | Behavior |
|--------|----------|
| `downloadDocumentsToKvs`: **false** or omitted | Links only (backward compatible). |
| `downloadDocumentsToKvs`: **true** | Fetches each PDF using the browser session, saves bytes to the default Key-Value Store, and adds `file_key` and `download_status`; on **Apify** runs, `file_url` points at the store record API. |

Some BOE PDFs require a **logged-in** session. Export [Playwright storage state](https://playwright.dev/docs/auth) after signing in at `subastas.boe.es`, upload that JSON as a Key-Value Store record, and set **`playwrightStorageStateKvsKey`** to that record key (or use **`playwrightStorageStateJson`** for inline JSON — prefer KVS for secrets). Sessions expire; if `download_status` is `not_pdf_maybe_login`, refresh the storage state.

Accessing `file_url` usually requires your **Apify API token** as the `token` query parameter on the Key-Value Store API, unless the store is configured for public access.

### 📦 Output Example

The scraper provides a clean, structured JSON dataset with keys in **Spanish**, ready for integration (see the Spanish section for a full JSON example, including optional `file_key` / `file_url` / `download_status` on documents).

# Actor input Schema

## `provincia` (type: `string`):

Province to search in. Select 'Todas las provincias' for all provinces.

## `tipoBien` (type: `string`):

Type of property. 'Todos' = Inmuebles, all subtypes (matches BOE 'Inmuebles, Todos').

## `estado` (type: `string`):

Status of the auction. 'Cualquiera' = all statuses.

## `valorMinimo` (type: `integer`):

Minimum appraised value (EUR).

## `valorMaximo` (type: `integer`):

Maximum appraised value (EUR).

## `soloHacienda` (type: `boolean`):

If true, only show auctions from the Tax Agency.

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

Maximum number of items to scrape. Set to 0 for no limit (all entries). Default 50.

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

Field used to order the BOE search results. 'identificador' descending returns the most recently published auctions first (ideal for incremental/daily runs). Default 'fecha_fin' matches BOE's default (auctions ending soonest first).

## `sortOrder` (type: `string`):

Order direction for 'Sort By'. Use 'desc' with 'identificador' to fetch newest auctions first and stop early via Max Items.

## `fechaInicioDesde` (type: `string`):

Optional. Filter by auction start date (Fecha inicio Subasta), from this date. Accepts YYYY-MM-DD or dd/mm/yyyy.

## `fechaInicioHasta` (type: `string`):

Optional. Filter by auction start date (Fecha inicio Subasta), up to this date. Accepts YYYY-MM-DD or dd/mm/yyyy.

## `fechaFinDesde` (type: `string`):

Optional. Filter by auction end date (Fecha fin Subasta), from this date. Accepts YYYY-MM-DD or dd/mm/yyyy.

## `fechaFinHasta` (type: `string`):

Optional. Filter by auction end date (Fecha fin Subasta), up to this date. Accepts YYYY-MM-DD or dd/mm/yyyy.

## `playwrightStorageStateKvsKey` (type: `string`):

After logging in to subastas.boe.es in a local browser, export Playwright storage state JSON and upload it to this run's Key-Value Store under this record name (e.g. boe-storage.json). Enables session cookies for gated PDFs.

## `playwrightStorageStateJson` (type: `string`):

Optional alternative to KVS key: paste full Playwright storage_state JSON here. Prefer KVS for large/secrets. Only one of KVS key or inline should be set.

## `downloadDocumentsToKvs` (type: `boolean`):

If true, fetch each document URL with the same browser session (cookies) and save PDFs to the default Key-Value Store. Requires storage state for gated PDFs. Adds file_url / download_status per document.

## Actor input object example

```json
{
  "provincia": "Todas las provincias",
  "tipoBien": "Vivienda",
  "estado": "Cualquiera",
  "soloHacienda": false,
  "maxItems": 50,
  "sortBy": "fecha_fin",
  "sortOrder": "asc",
  "downloadDocumentsToKvs": false
}
```

# 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("signalflow/spain-auction-scout").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("signalflow/spain-auction-scout").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 signalflow/spain-auction-scout --silent --output-dataset

```

## MCP server setup

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

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/fHQb53czwbD3uxjXJ/builds/cIUjjPyDWKtZxjl3e/openapi.json
