# Fotocasa Scraper — Spain Property Listings (`stone_jadex/fotocasa-es-scraper`) Actor

Export public Fotocasa.es sale and rental listings: price, rooms, baths, m², district, coordinates, agency and its public phones. Optional detail tier adds energy certificate. $0.50 per 1,000 listings ($1.50 with detail) plus $0.0005 per run.

- **URL**: https://apify.com/stone_jadex/fotocasa-es-scraper.md
- **Developed by:** [Stone Jade](https://apify.com/stone_jadex) (community)
- **Categories:** Real estate, Lead generation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.43 / 1,000 list-tier listings

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## Fotocasa Spain Property Scraper — listings at $0.50 per 1,000

**For agencies, relocation teams, investors and market analysts who need public Fotocasa.es sale and rental listings as a dataset they can sort, map and compare.**

Paste a Fotocasa search URL for a city or area (rent or buy), or leave the input empty for Madrid rentals. Each row is one listing with asking price, rooms, bathrooms, built area, district and neighbourhood, coordinates, agency name, public agency phone numbers and the listing link. An optional detail tier opens each listing page to add the energy certificate and fuller contact data when the search card is thin.

Each run is a snapshot of the search at that moment. Start with the default 50 Madrid rentals to see the columns before a larger run.

### What you gain

- **Comparable listings without copying cards** — price, rooms, bathrooms and m² arrive as numbers, so you can compute price per m² or filter a neighbourhood in a spreadsheet.
- **Location you can map** — city, district, neighbourhood, postcode and latitude/longitude sit on each row for maps and local comparisons.
- **A contact list of advertising agencies** — the agency name and the business phone numbers published on the listing come with each row; private sellers' phones and emails are removed.
- **One clean row per listing** — listings are keyed by Fotocasa's listing ID, and a listing that appears twice in a run is saved once.
- **Direct HTTP execution at 256 MB memory** — extracts embedded page-1 JSON and Fotocasa's public property-search gateway JSON from page 2 onward without headless browser overhead.

### Built for these workflows

#### Relocation consultant shortlisting rentals

A relocation team runs a Madrid or Barcelona rental search before a client visit, filters by monthly rent, rooms and neighbourhood, and sends the shortlisted Fotocasa links to the client.

#### Market analyst tracking asking prices

An analyst collects a city's sale search each month, computes median asking price per m² by district in their BI tool, and compares months over time.

#### Agency or proptech team building a lead list

A business-development team groups listings by agency to see which agencies advertise the most stock in a district, then contacts them through the published business phone numbers.

#### Automated portfolio & BI ingestion

An engineering team schedules runs through the Apify API or official JavaScript and Python clients, storing normalized JSON rows directly in PostgreSQL, BigQuery, or Airtable while reading the `OUTPUT` status summary after each run.

### Preview what you receive

Real rows parsed from a saved Fotocasa Madrid rentals search page, captured on 2026-10-26 (UTC+8). Prices are monthly rents in EUR; area is built m².

| Listing ID | Listing | Rent (EUR / month) | Rooms | Baths | m² | Neighbourhood (district) | Agency |
|---|---|---:|---:|---:|---:|---|---|
| 190709164 | Flat · 4 hab. · 135 m² · Guindalera | 2,800 | 4 | 2 | 135 | Guindalera (Barrio de Salamanca) | ENGEL & VÖLKERS MADRID |
| 189720360 | Attic · 2 hab. · 97 m² · Argüelles | 2,300 | 2 | 1 | 97 | Argüelles (Moncloa - Aravaca) | Aldebaran Inmobiliaria |
| 188242983 | Flat · 1 hab. · 42 m² · Castellana | 1,490 | 1 | 1 | 42 | Castellana (Barrio de Salamanca) | Ginmo |
| 190836473 | Duplex · 1 hab. · 45 m² · Sol | 1,195 | 1 | 1 | 45 | Sol (Centro) | Casas y Más |

Each row also carries the listing URL, coordinates, postcode, floor, photos, published agency phones, description text where the card has one, and the search page and position it came from. On the detail tier, a saved agency listing page (2026-10-26) added energy rating `G` and the agency phone published on that page. Export as JSON, CSV or Excel.

Fields stay empty when Fotocasa does not publish them: the energy certificate is usually only on the listing page, and search results from page 2 onward sometimes omit the property type.

#### Illustrative JSON Output Example

The illustrative record below conforms strictly to the dataset schema (including all core search-card attributes plus detail-tier energy fields when `scrapeDetails` is enabled; private seller rows automatically clear `phones` and `emails` to empty arrays):

```jsonc
{
  "listingId": "190709164",
  "realEstateAdId": "00000000-0000-4000-8000-000000000000",
  "title": "Flat · 4 hab. · 135 m² · Guindalera",
  "price": 2800,
  "currency": "EUR",
  "pricePeriod": "month",
  "rooms": 4,
  "baths": 2,
  "area_m2": 135,
  "floor": 6,
  "propertyType": "Flat",
  "propertySubtype": "Flat",
  "operation": "rent",
  "city": "Madrid",
  "district": "Barrio de Salamanca",
  "neighborhood": "Guindalera",
  "province": "Madrid",
  "address": "Guindalera",
  "zipCode": "28028",
  "lat": 40.437243,
  "lon": -3.676576,
  "agency": "ENGEL & VÖLKERS MADRID",
  "agent": null,
  "isPrivateOwner": false,
  "phones": [
    "+34912774500"
  ],
  "emails": [],
  "energyRating": "G",
  "energyValue": 123,
  "photos": [
    "https://static.fotocasa.es/images/ads/example-photo-1.jpg",
    "https://static.fotocasa.es/images/ads/example-photo-2.jpg"
  ],
  "description": "Renovated family apartment in Barrio de Salamanca (Guindalera) with terrace and air conditioning.",
  "url": "https://www.fotocasa.es/es/alquiler/vivienda/madrid-capital/aire-acondicionado-calefaccion-ascensor-patio-se-aceptan-mascotas-no-amueblado/190709164/d",
  "publicationDate": "2026-09-09T11:05:02.573",
  "page": 1,
  "position": 1,
  "listUrl": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l",
  "tier": "detail",
  "scrapedAt": "2026-11-24T00:00:00.000Z"
}
```

#### Uncharged Run-Notice Row

When a run ends early (for example at `maxItems`, `max-charge-reached`, `proxy-budget`, `run-time-limit`, or a stop condition), one uncharged summary row is appended to the dataset:

```jsonc
{
  "recordType": "run-notice",
  "truncatedAfter": 50,
  "reason": "maxItems"
}
```

#### Complete Dataset Field Reference

Every property declared in the dataset schema (41 fields total) is documented below. Listing fields are nullable when omitted by Fotocasa.es.

| Field | Type | Tier | Description |
| --- | --- | --- | --- |
| `listingId` | string or null | List, Detail | Fotocasa property ID used to deduplicate listings within a run. |
| `realEstateAdId` | string or null | List, Detail | UUID ad ID published by Fotocasa when available. |
| `title` | string or null | List, Detail | Published listing headline or constructed summary title (type, rooms, area, location). |
| `price` | number or null | List, Detail | Asking sale or monthly rental price amount without currency symbol. |
| `currency` | string or null | List, Detail | Currency code for the price (EUR for Fotocasa.es listings). |
| `pricePeriod` | string or null | List, Detail | Billing period for rentals (such as month); null for sale listings. |
| `rooms` | number or null | List, Detail | Number of bedrooms/rooms when published. |
| `baths` | number or null | List, Detail | Number of bathrooms when published. |
| `area_m2` | number or null | List, Detail | Built area in square meters when published. |
| `floor` | number or null | List, Detail | Floor number when published (0 indicates ground floor). |
| `propertyType` | string or null | List, Detail | Building type published by Fotocasa (such as Flat); sometimes omitted by gateway JSON on page 2+. |
| `propertySubtype` | string or null | List, Detail | Published property subtype (such as Apartment) when available. |
| `operation` | string or null | List, Detail | Normalized transaction operation: rent or sale. |
| `city` | string or null | List, Detail | City or municipality name from the listing address. |
| `district` | string or null | List, Detail | Municipal district name from the listing address. |
| `neighborhood` | string or null | List, Detail | Neighbourhood or upper-level area text when published. |
| `province` | string or null | List, Detail | Province name from the listing address when published. |
| `address` | string or null | List, Detail | Street address when published; null when Fotocasa only exposes neighbourhood/district. |
| `zipCode` | string or null | List, Detail | Spanish postal code when published. |
| `lat` | number or null | List, Detail | Latitude coordinate when published. |
| `lon` | number or null | List, Detail | Longitude coordinate when published. |
| `agency` | string or null | List, Detail | Advertising real estate agency or publisher name when published. |
| `agent` | string or null | Detail (when published) | Public contact name shown on the listing detail page when available. |
| `isPrivateOwner` | boolean or null | List, Detail | True when advertiser is a private owner (particular); false for commercial agencies; null when unknown. |
| `phones` | array of strings or null | List, Detail | Public commercial/agency phone numbers; private seller phones are dropped. |
| `emails` | array of strings or null | List, Detail | Public commercial/agency email addresses; private seller emails are dropped. |
| `energyRating` | string or null | Detail (usually) | Energy efficiency rating letter (e.g. A through G) when published, usually on the detail page. |
| `energyValue` | number or null | Detail (usually) | Published numeric energy efficiency value when available. |
| `photos` | array of strings or null | List, Detail | Array of published image URLs for the listing. |
| `description` | string or null | List, Detail | Plain-text listing description (enriched with full text on the detail tier). |
| `url` | string or null | List, Detail | Canonical public listing URL on fotocasa.es. |
| `publicationDate` | string or null | List, Detail | Publication timestamp text exactly as published by the source. |
| `page` | integer or null | List, Detail (from list) | Search page number where the listing was discovered; absent on direct detail seeds. |
| `position` | integer or null | List, Detail (from list) | One-based position of the listing on its search page; absent on direct detail seeds. |
| `listUrl` | string or null | List, Detail | Search or direct listing URL from which the row was discovered. |
| `tier` | string or null | List, Detail | Extraction tier for the row: list (search card or fallback) or detail (detail-page enriched). |
| `scrapedAt` | string or null | List, Detail | ISO 8601 UTC timestamp recording when the row was scraped. |
| `detailError` | string or null | List (fallback) | Error string recorded when `scrapeDetails` failed and the search-card row was kept at list pricing. |
| `recordType` | string or null | Run-notice | Set to run-notice on the optional uncharged truncation row; absent on listing rows. |
| `truncatedAfter` | integer or null | Run-notice | Number of charged listing rows saved before truncation. |
| `reason` | string or null | Run-notice | Stop reason for truncation (such as `maxItems` or `run-time-limit`). |

#### Dataset Views & Key-Value Store Summary

- **Overview view**: Compact Console table showing `listingId`, `title`, `price`, `currency`, `operation`, `rooms`, `baths`, `area_m2`, `city`, `neighborhood`, `agency`, `tier`, and `url`.
- **Listings view**: Full 37-column property table covering identity, pricing, dimensions, multi-level Spanish geography, contacts, energy ratings, media, and detail status.
- **Run notices view**: Displays `recordType`, `truncatedAfter`, and `reason` for truncated runs.
- **Key-Value Store OUTPUT record**: Summarizes seeds, pushed counts, duplicatesSkipped, pagesFetched, siteTotalEntries, listSource (HTML vs gateway JSON counts), unavailableFields, http transfer counters, robots metadata, `robotsDisallowedHits`, `errors`, `stopReason`, `failed`, `runNotice`, `lastFailure`, `deadlineSource`, and `pricingEvents`.

### Why choose this Actor

- **Search pages beyond page 1 without the blocked HTML paths** — page 1 is read from the public search page and later pages from the public property-search data the Fotocasa site itself loads, about 30 listings per page.
- **Detail only where you want it** — the energy certificate and fuller contacts cost more per row only when you turn the detail tier on; a listing page that fails still returns the search-card row at the list price.
- **Privacy handled at the source** — business contacts published by agencies are kept as shown; private sellers' phone numbers and emails are dropped before the row is saved.
- **Built-in 5 MB residential bandwidth guardrail** — stays on a direct connection by default; if you configure a residential proxy with `useProxyFallback`, transfer is capped at 5 MB per run and detail pages stay direct unless `allowDetailOnResidential` is explicitly enabled.

### Pricing

Prices in **USD**. Check the current Pricing tab before running.

| Charge | Price |
|---|---:|
| Listing (search results) | $0.50 per 1,000 listings ($0.0005 per listing) |
| Listing with detail page | $1.50 per 1,000 listings ($0.0015 per listing) |
| Run start | $0.0005 per run |

A listing with its detail page is charged at the detail price **instead of** the list price, not on top. If a listing page fails, that row keeps its search-card data and is charged at the list price. The run start fee is charged once by Apify when a run starts at the default 256 MB memory (Apify adds one start fee for each extra GB if you give a run more than 1 GB). You are charged for listings saved to the dataset; a duplicate listing in the same run is not saved or charged twice, and the notice row added when a run stops early is free.

**What you pay:** under this Actor's pay-per-event pricing you pay the event prices above; the platform compute used by the run is not billed to you separately, unless the Actor's Pricing tab says usage is added on top. Reading, exporting or writing stored data after the run has finished is billed as platform usage on your own Apify plan.

Example: 1,000 search-result listings cost $0.50 plus $0.0005 for the start, $0.5005 in total; with the detail tier on for all 1,000, $1.50 plus $0.0005, $1.5005. A run that saves no listings has no listing charges, but the start fee still applies.

**Compared with igolaizola/fotocasa-scraper:** its public Apify Store listing (checked on 16 November 2026) charges $0.001 per result plus $0.001 per run start on the Apify Free plan ($0.0009 each on Bronze, $0.0008 on Silver, $0.0007 on Gold and above), so 1,000 results cost $1.001 on the Free plan. This Actor's search-result tier costs $0.5005 for 1,000 listings, which is 50% of the competitor's Free-plan price.

#### Apify Store Subscription Tier Discounts (Bronze to Diamond)

Apify Store subscription plans automatically apply **5% to 15% discounts** across every Pay-Per-Event charge:

| Event | Free (1.00x) | Bronze (5% off) | Silver (10% off) | Gold / Platinum / Diamond (15% off) |
| --- | ---: | ---: | ---: | ---: |
| Listing (search results, primary) | $0.0005 ($0.50/1k) | $0.000475 ($0.475/1k) | $0.00045 ($0.45/1k) | $0.000425 ($0.425/1k) |
| Listing with detail page | $0.0015 ($1.50/1k) | $0.001425 ($1.425/1k) | $0.00135 ($1.35/1k) | $0.001275 ($1.275/1k) |
| Run start (per GB, min 1 at 256 MB) | $0.0005 | $0.000475 | $0.00045 | $0.000425 |

### Get started in three steps

1. Leave **Search or listing URLs** empty for Madrid rentals, or paste a Fotocasa search URL such as `https://www.fotocasa.es/es/comprar/viviendas/barcelona-capital/todas-las-zonas/l`.
2. Set **Max listings** (default 50, up to 2,000). Turn on **Open each listing page** only if you need energy certificates and fuller contacts; then run.
3. Open the dataset, check the rows, and export them as JSON, CSV or Excel.

```json
{
  "startUrls": [{ "url": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l" }],
  "maxItems": 100,
  "scrapeDetails": false
}
```

#### Input Configuration Reference

All input fields are optional. Running with empty input {} starts with Madrid rental apartments (`maxItems`: 50, `scrapeDetails`: false, direct HTTP connection).

| Parameter | Type | Default | Constraints | Description |
| --- | --- | --- | --- | --- |
| `startUrls` | array | Madrid rental search | Public fotocasa.es `/l` search or `/d` listing URLs | **Target URLs & Pagination.** Search URLs or direct listing URLs. Accepts Request List objects or plain URL strings. |
| `maxItems` | integer | 50 | Min 1, Max 2000 | **Target URLs & Pagination.** Maximum unique listings to emit before stopping cleanly. |
| `maxPages` | integer | null (unlimited) | Min 1, Max 2000 | **Target URLs & Pagination.** Optional cap on search pages per seed (~30 listings/page; page 2+ uses gateway JSON). |
| `startPage` | integer | 1 | Min 1, Max 2000 | **Target URLs & Pagination.** Starting page when the search URL does not already include `/l/N`. |
| `scrapeDetails` | boolean | false | true / false | **Detail Enrichment.** Open each listing page for energy certificates, fuller descriptions, and contact details (billed as listing-detail instead of listing). |
| `requestDelayMs` | integer | 1200 | Min 1200 | **Rate Limiting & Runtime.** Minimum milliseconds between HTTP request starts. Raised automatically if robots.txt Crawl-delay is higher. |
| `concurrency` | integer | 1 | Min 1, Max 3 | **Rate Limiting & Runtime.** Requests in flight simultaneously while keeping page order and start spacing. |
| `maxRunSeconds` | integer | 3600 | Min 30 | **Rate Limiting & Runtime.** Clean shutdown deadline in seconds before platform timeout. |
| `proxyConfiguration` | object | { "useApifyProxy": false } | Apify Proxy config | **Proxy Settings.** Direct by default. Residential proxies are capped at 5 MB per run and intended as fallback only. |
| `useProxyFallback` | boolean | false | true / false | **Proxy Settings.** Stay direct until repeated HTTP 403 or 429 blocks, then switch to the configured proxy. |
| `allowDetailOnResidential` | boolean | false | true / false | **Proxy Settings.** Keep detail pages direct when using residential proxy unless explicitly turned on. |

#### Input Example 2: Barcelona Sale Search, Direct Listing URL & Detail Enrichment

Collect up to 150 Barcelona homes for sale plus a specific listing URL with energy ratings (`scrapeDetails`: true) and proxy fallback enabled:

```json
{
  "startUrls": [
    { "url": "https://www.fotocasa.es/es/comprar/viviendas/barcelona-capital/todas-las-zonas/l" },
    { "url": "https://www.fotocasa.es/es/alquiler/vivienda/madrid-capital/aire-acondicionado-calefaccion-ascensor-patio-se-aceptan-mascotas-no-amueblado/190709164/d" }
  ],
  "maxItems": 150,
  "maxPages": 6,
  "startPage": 1,
  "scrapeDetails": true,
  "requestDelayMs": 1500,
  "concurrency": 2,
  "maxRunSeconds": 1800,
  "useProxyFallback": true,
  "proxyConfiguration": { "useApifyProxy": false }
}
```

#### JavaScript (Node.js) — ApifyClient Quickstart

Install the Apify JavaScript client (**npm install apify-client**), set APIFY_TOKEN, and run Stone_JadeX/fotocasa-es-scraper programmatically:

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

const client = new ApifyClient({
    token: process.env.APIFY_TOKEN,
});

const run = await client.actor('Stone_JadeX/fotocasa-es-scraper').call({
    startUrls: [
        { url: 'https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l' },
    ],
    maxItems: 50,
    scrapeDetails: false,
    requestDelayMs: 1200,
    concurrency: 1,
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
const listings = items.filter((row) => row.recordType !== 'run-notice');
console.log('Collected listings:', listings.length);
for (const row of listings.slice(0, 5)) {
    console.log(row.listingId, row.title, row.price, row.currency, row.area_m2, row.neighborhood);
}

const outputRecord = await client.keyValueStore(run.defaultKeyValueStoreId).getRecord('OUTPUT');
console.log('Stop reason:', outputRecord?.value?.stopReason, 'Failed:', outputRecord?.value?.failed);
```

#### Python — ApifyClient Quickstart

Install the Apify Python client (**pip install apify-client**), export APIFY_TOKEN, and run:

```python
import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])

run = client.actor("Stone_JadeX/fotocasa-es-scraper").call(run_input={
    "startUrls": [
        {"url": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l"},
    ],
    "maxItems": 50,
    "scrapeDetails": False,
    "requestDelayMs": 1200,
    "concurrency": 1,
})

items = [
    row for row in client.dataset(run["defaultDatasetId"]).iterate_items()
    if row.get("recordType") != "run-notice"
]
print("Collected listings:", len(items))
for row in items[:5]:
    print(row.get("listingId"), row.get("title"), row.get("price"), row.get("currency"), row.get("neighborhood"))

output_record = client.key_value_store(run["defaultKeyValueStoreId"]).get_record("OUTPUT")
print("Stop reason:", (output_record or {}).get("value", {}).get("stopReason"))
```

### Coverage and common questions

The Actor reads public Fotocasa.es search pages, the public property-search data those pages load, and, on the detail tier, public listing pages. It does not log in, use accounts or solve captchas. It covers Fotocasa.es only.

#### Which searches are supported?

Search URLs for homes to rent (`/es/alquiler/…/l`) or buy (`/es/comprar/…/l`) and single listing URLs ending in `/d`. The Actor follows the location, rent or buy choice and property type in the URL path; filters in the URL's query string (for example a price range) are not applied, so filter the dataset afterwards.

#### How many listings can I get?

About 30 per search page, up to 2,000 per run. Max listings is a ceiling, not a guaranteed count; the run stops earlier when the search runs out of results or a page comes back empty.

#### How does it treat robots.txt?

robots.txt is read at the start of every run and any crawl-delay is followed. HTML list paths `/l/2`–`/l/39` are Disallow'd and the Actor does not use them: later pages use the site's public `web.gw.fotocasa.es` property-search JSON instead.
If a requested URL matches a Disallow rule, it is still requested, logged as a warning and counted in `robotsDisallowedHits`.

#### What if Fotocasa blocks the run?

Requests start at least 1.2 seconds apart, one at a time by default. On HTTP 403, 412 or 429 the Actor waits 30 seconds, then 60 seconds, and retries. If the request is still blocked, or a retry after a block ends with another error, a timeout or a network error, the whole run currently stops, not just that search, with `stopReason` `blocked-403`, `blocked-412` or `blocked-429`. A Cloudflare challenge page is never solved or bypassed; it stops the whole run as `blocked-challenge`. If too little run time is left for a wait, the run stops as blocked without waiting. In these cases the run summary has `failed` set to true, the platform run status is still SUCCEEDED, and the status message reads "Stopped (<stopReason>)". Listings saved before the stop are kept and charged; on the detail tier, the search-card row of a blocked listing page is saved at the list price before the run stops. Proxy is off by default. If you add Apify Proxy and turn on **Use proxy only after repeated blocks**, the run switches to it after repeated blocks; residential proxy traffic is capped at 5 MB per run, and the run stops when the cap is reached.

#### How do I know whether a run finished completely?

Every run writes a summary to the OUTPUT record of its key-value store. `stopReason` says why the run ended, `failed` says whether it ended because of a problem, and each entry in `errors` carries `type`, `url` and `lastFailure`.

- **Not failed, status message starts with "Done":** `completed` (the searches finished), `maxItems`, `empty` (no listings and no errors), `max-charge-reached` (your maximum cost per run was reached), `proxy-budget` (the 5 MB residential cap), `run-time-limit` when your **Max run time (seconds)** came first, and `charge-error` (a charge could not be recorded, so the run stopped; listings from that batch are not counted in the summary).
- **Failed, status message "Stopped (<stopReason>)":** the blocked reasons above, `errors` (a search page failed for a reason other than a block), `error` (an unexpected error stopped the run) and `run-time-limit` when the platform timeout came first (`deadlineSource` is `hard-timeout`).

The platform run status is SUCCEEDED in all of these cases; only invalid input makes the run itself fail. With several search URLs, a search page that fails for a reason other than a block (for example a 404 or repeated server errors) currently stops only that search, and the run moves on to the next URL. If a later search then ends the run, for example at Max listings, that reason becomes the `stopReason` and `failed` can be false, so the earlier failure shows only in `errors`. On multi-search runs, check `errors` as well as `stopReason`. A detail page that fails without a block is also listed in `errors` while its row is saved at the list price.

When the platform timeout is reached, the run currently waits up to 3 seconds for listings still being written. Listings not confirmed in that time are not charged and not counted in the summary, but they may still appear in the dataset.

#### Is this a monitoring service?

No. Each run captures what the search showed at that time. Listings can change or disappear afterwards; schedule and compare runs in your own workflow if you need tracking.

#### Changelog

- **0.2.2 (2026-11-24)**: Merged v0.2.1 reliability & block-rule upgrades onto latest; added sectionCaption groups and explicit prefill defaults across input schema; enabled Apify Store subscription tier discounts (Bronze 5% off to Gold/Platinum/Diamond 15% off) with list-tier listing marked as the primary event; expanded Store documentation with 41-field schema reference, illustrative JSON output, and JavaScript/Python ApifyClient quickstarts.
- **0.2.1 (2026-11-16)**: Implemented unified 403/412/429 backoff and `blocked-403` / `blocked-412` / `blocked-429` / `blocked-challenge` end states, H6/H7 3-second in-flight write confirmation before hard-deadline exit, status message alignment, detail-tier rate alignment ($0.0015), and `apify-actor-start` ($0.0005).
- **0.1.0 (2026-10-26)**: Initial Fotocasa.es scraper reading HTML page 1 and public `web.gw.fotocasa.es` JSON for page 2+, dropping private seller phones and emails, and enforcing a 5 MB residential proxy ceiling.

This is an independent tool and is not affiliated with Fotocasa. Start with the default Madrid rentals, then point it at your own city search.

# Changelog

This Actor's version history is a separate document: https://apify.com/stone_jadex/fotocasa-es-scraper/changelog.md

# Actor input Schema

## `startUrls` (type: `array`):

Optional. A Fotocasa search URL such as https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l, or a listing URL ending in /{id}/d. Empty input uses Madrid rentals (viviendas).

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

Stop after this many listings.

## `maxPages` (type: `integer`):

Optional. Each search page has about 30 listings. Pages after the first are loaded from Fotocasa's public property-search JSON (HTML /l/2+ is Disallow'd in robots.txt).

## `startPage` (type: `integer`):

First search page when the start URL does not already set /l/N.

## `scrapeDetails` (type: `boolean`):

Adds energy certificate, richer contacts, and the published description when the detail page has more than the list card. Charged as listing-detail instead of listing. If a detail page fails, the list row is kept and charged as listing.

## `requestDelayMs` (type: `integer`):

At least 1.2 seconds between request starts. A Crawl-delay in robots.txt can only raise this.

## `concurrency` (type: `integer`):

How many search or detail pages may be requested at once. Rows are saved in page order. At least 1.2 seconds still pass between request starts.

## `maxRunSeconds` (type: `integer`):

Stops cleanly and writes the OUTPUT record before this limit.

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

Direct connection by default. Do not default to residential. A residential proxy is a fallback only (turn on useProxyFallback) and is capped at a fixed 5 MB per run.

## `useProxyFallback` (type: `boolean`):

When a proxy is configured, stay on a direct connection until repeated HTTP 403 or 429 responses, then switch to that proxy. A residential proxy is meant to be used this way, as a fallback — never as the default.

## `allowDetailOnResidential` (type: `boolean`):

Detail pages stay on a direct connection when the proxy group is residential. Turn this on only if those detail pages should use the residential proxy too.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l"
    }
  ],
  "maxItems": 50,
  "startPage": 1,
  "scrapeDetails": false,
  "requestDelayMs": 1200,
  "concurrency": 1,
  "maxRunSeconds": 3600,
  "proxyConfiguration": {
    "useApifyProxy": false
  },
  "useProxyFallback": false,
  "allowDetailOnResidential": false
}
```

# Actor output Schema

## `listings` (type: `string`):

Charged Fotocasa.es listing rows from the default dataset, including list-tier rows and detail-enriched rows. A shortened run also adds one uncharged run-notice row.

## `summary` (type: `string`):

Run statistics, seed results, errors, run input, pricing, unavailable fields, and the stop reason stored as JSON under the OUTPUT key. stopReason values: blocked-403 / blocked-412 / blocked-429 / blocked-challenge, errors (list-error) and error (unknown exception in the main loop) have failed=true; run-time-limit has failed=true when deadlineSource=hard-timeout and failed=false when deadlineSource=maxRunSeconds; empty, completed, maxItems, max-charge-reached, proxy-budget and charge-error have failed=false; invalid-input has failed=true and still calls Actor.fail after writing OUTPUT. The platform run is otherwise SUCCEEDED. errors\[].type is blocked / blocked-challenge / list-error / detail-error / error / charge-error, each with url and lastFailure (HTTP status number, or timeout / network-error, or the error message for error / charge-error). Also runNotice, failed, deadlineSource and pricingEvents.start=apify-actor-start (platform synthetic start event, never charged by this code). On a hard deadline the timer waits up to 3 s for in-flight pushData/charge; writes not confirmed in that window are not charged and are not counted in OUTPUT (they may still appear in the dataset). After OUTPUT and the run-notice row are written, the platform status message is Stopped (<stopReason>) when out.failed is true, otherwise Done. cloudflare-challenge, site-end and empty-page are no longer written (a natural search end is completed; a successful empty list page ends that search). The Actor does not write a RUN_SUMMARY key.

## `results` (type: `string`):

Default dataset: one row per scraped item (plus an uncharged run-notice row if the run stopped early).

## `overview` (type: `string`):

Default dataset in the overview table view.

# 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 = {
    "startUrls": [
        {
            "url": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l"
        }
    ],
    "maxItems": 50,
    "startPage": 1,
    "scrapeDetails": false,
    "requestDelayMs": 1200,
    "concurrency": 1,
    "maxRunSeconds": 3600,
    "proxyConfiguration": {
        "useApifyProxy": false
    },
    "useProxyFallback": false,
    "allowDetailOnResidential": false
};

// Run the Actor and wait for it to finish
const run = await client.actor("stone_jadex/fotocasa-es-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 = {
    "startUrls": [{ "url": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l" }],
    "maxItems": 50,
    "startPage": 1,
    "scrapeDetails": False,
    "requestDelayMs": 1200,
    "concurrency": 1,
    "maxRunSeconds": 3600,
    "proxyConfiguration": { "useApifyProxy": False },
    "useProxyFallback": False,
    "allowDetailOnResidential": False,
}

# Run the Actor and wait for it to finish
run = client.actor("stone_jadex/fotocasa-es-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 '{
  "startUrls": [
    {
      "url": "https://www.fotocasa.es/es/alquiler/viviendas/madrid-capital/todas-las-zonas/l"
    }
  ],
  "maxItems": 50,
  "startPage": 1,
  "scrapeDetails": false,
  "requestDelayMs": 1200,
  "concurrency": 1,
  "maxRunSeconds": 3600,
  "proxyConfiguration": {
    "useApifyProxy": false
  },
  "useProxyFallback": false,
  "allowDetailOnResidential": false
}' |
apify call stone_jadex/fotocasa-es-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,stone_jadex/fotocasa-es-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/b87Y7xNwA7Niv1r0E/builds/ow8SL820oAghzeYvM/openapi.json
