# Habitaclia.com Real Estate Scraper (Spain) (`stone_jadex/habitaclia-com-scraper`) Actor

Public Habitaclia.com property listings from search results: price, rooms, baths, area, location, agency, photos, and optional detail page. No start fee.

- **URL**: https://apify.com/stone_jadex/habitaclia-com-scraper.md
- **Developed by:** [Stone Jade](https://apify.com/stone_jadex) (community)
- **Categories:** Real estate
- **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

## Habitaclia.com Real Estate Scraper (Spain)

Extract structured residential property listings from **Habitaclia.com**, one of Spain's leading real estate portals, directly into clean JSON, CSV, Excel, or API pipelines. Collect asking rents and sale prices, room and bathroom counts, built and land area, multi-level Spanish locations, energy efficiency ratings, amenities, photos, and public agency contacts—with **zero run-start fees** and lightweight 256 MB HTTP execution.

***

### Overview & Key Features

**Habitaclia.com Real Estate Scraper** extracts public rent (`/alquiler/.../s`) and sale (`/comprar/.../s`) property listings as well as direct detail URLs (`/…/{uuid}/d`) by reading the structured `window.__INITIAL_PROPS__` JSON payload embedded directly in public Habitaclia pages—no headless browser needed.

Unlike many property portals where search cards omit key metadata, Habitaclia search result pages (~29 listings per page, paginated via `/s` and `/s/N`) already include rich descriptions, energy certificate ratings and CO2 emissions, feature tags, photo galleries, and public agency contacts. Leaving `scrapeDetails` off captures the complete search-card payload at full speed, while enabling `scrapeDetails: true` re-fetches each public detail page to confirm the detail embed.

#### Key Capabilities

- **Zero start fee, flat transparent pricing**: Both list-tier (`listing`) and detail-tier (`listing-detail`) events cost **$0.0005** per result (**$0.50** per 1,000 listings on the Free tier, with 5%–15% Apify Store subscription discounts for Bronze through Diamond), with **$0.00** start fee.
- **Rich list-tier payloads out of the box**: Even with `scrapeDetails: false`, each row captures `listingId`, `legacyNumericId`, `reference`, `title`, `price`, `currency`, `pricePeriod`, `rooms`, `baths`, `area_m2`, `landArea_m2`, `floor`, `constructionYear`, `propertyType`, `propertySubtype`, `propertyStatus`, `operation`, `city`, `district`, `neighborhood`, `province`, `address`, `zipCode`, `lat`, `lon`, `agency`, `agent`, `agencyWebsite`, `isPrivateOwner`, `phones`, `emails`, `energyRating`, `energyValue`, `energyEmissionsRating`, `energyEmissionsValue`, `features`, `photos`, `description`, and canonical `url`.
- **Built-in privacy filtering (Privacy Policy A)**: Public commercial agency phone numbers, emails, and websites printed in `__INITIAL_PROPS__` are retained, while private owner (`particular`) phone numbers and email addresses are automatically dropped (`isPrivateOwner: true` rows always output `phones: []` and `emails: []`). The Actor never calls disallowed phone-reveal or AJAX endpoints.
- **Page-ordered output & graceful truncation**: Even when `concurrency` is increased up to `3`, rows are saved in page order, duplicate listing UUIDs across overlapping seeds are skipped without charging, and early stops append a single uncharged `recordType: "run-notice"` row plus a complete `OUTPUT` summary in the Key-Value Store.

#### Common Use Cases

- **Spanish residential market & rent benchmarking**: Compare monthly rents (`operation: "rent"`, `pricePeriod: "month"`) and sale prices (`operation: "sale"`) across Barcelona, Madrid, Valencia, Seville, Málaga, or any province/municipality on Habitaclia.com.
- **Energy certificate & building quality analytics**: Analyze `energyRating`, `energyValue`, `energyEmissionsRating`, `energyEmissionsValue`, `constructionYear`, `propertyStatus`, and `features` (`ELEVATOR`, `TERRACE`, `AIR_CONDITIONER`, `PRIVATE_PARKING`, etc.) across neighbourhoods.
- **Agency & portfolio intelligence**: Track brokerage inventory using `agency`, `agent`, `agencyWebsite`, `reference`, and `legacyNumericId`.
- **Geospatial housing maps**: Use `lat`, `lon`, `district`, `neighborhood`, `city`, and `province` coordinates for GIS mapping and local comp engines.

***

### Input Configuration

All input fields are optional. Running with an empty input (`{}`) automatically scrapes Habitaclia's public rental apartment searches (`viviendas`) in both **Barcelona** and **Madrid** (`https://www.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s` and `https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s`) up to `50` listings total.

| Parameter | Type | Default | Constraints | Description |
| --- | --- | --- | --- | --- |
| `startUrls` | `array<object \| string>` | Barcelona + Madrid rental searches | Public `habitaclia.com` search (`/…/s` or `/…/s/N`) or detail (`/…/{uuid}/d`) URLs | Search result URLs or direct listing detail URLs. Accepts Request List `{ "url": "..." }` objects or plain URL strings. |
| `maxItems` | `integer` | `50` | Min `1`, Max `2000` | Maximum number of charged listings to collect across all seeds before stopping cleanly. |
| `maxPages` | `integer` | `null` (unlimited) | Min `1`, Max `2000` | Optional cap on search result pages fetched per list seed (~29 listings per page). |
| `startPage` | `integer` | `1` | Min `1`, Max `2000` | First search page number when the start URL does not already specify `/s/N`. |
| `scrapeDetails` | `boolean` | `false` | `true` / `false` | Re-fetches each listing's public detail page to confirm the detail embed (`tier: "detail"`). Charged as `listing-detail` instead of `listing`. Failed detail fetches preserve the list row (`detailError`) charged as `listing`. |
| `requestDelayMs` | `integer` | `1200` | Min `1200` | Minimum interval in milliseconds between HTTP request starts. A `Crawl-delay` directive in `robots.txt` can only raise this gap. |
| `concurrency` | `integer` | `1` | Min `1`, Max `3` | Maximum search or detail requests in flight simultaneously. Rows are still emitted in page order while spacing request starts by at least `requestDelayMs`. |
| `maxRunSeconds` | `integer` | `3600` | Min `30` | Graceful run-time budget in seconds. Stops ahead of platform timeout, writes `OUTPUT`, and appends an uncharged `run-notice` row when truncated. |
| `proxyConfiguration` | `object` | `{ "useApifyProxy": false }` | Apify Proxy config | Direct connection by default. Do not default to residential proxies. If a `RESIDENTIAL` proxy group is used, transfer is strictly capped at a fixed **5 MB per run** (not user-tunable). |
| `useProxyFallback` | `boolean` | `false` | `true` / `false` | When a proxy is configured, remain on a direct connection until repeated HTTP `403` or `429` responses occur, then switch to the configured proxy. Recommended whenever using residential proxies. |
| `allowDetailOnResidential` | `boolean` | `false` | `true` / `false` | When using a `RESIDENTIAL` proxy group, detail pages stay on direct connections by default. Enable only if detail requests should also route through the residential proxy within the 5 MB cap. |

#### Example 1: List-Tier Search (Barcelona & Madrid Rentals)

Fast list-tier collection of up to 200 rental listings across Barcelona and Madrid directly from search result pages:

```json
{
  "startUrls": [
    {
      "url": "https://www.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s"
    },
    {
      "url": "https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s"
    }
  ],
  "maxItems": 200,
  "maxPages": 4,
  "startPage": 1,
  "scrapeDetails": false,
  "requestDelayMs": 1200,
  "concurrency": 1,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

#### Example 2: Sale Search with Detail-Embed Confirmation & Direct Listing URL

Collect homes for sale (`comprar`) in Valencia alongside a specific listing URL with `scrapeDetails: true` and proxy fallback enabled:

```json
{
  "startUrls": [
    {
      "url": "https://www.habitaclia.com/alquiler/planta-intermedia/carrer-del-capita-arenas-3/les-corts/barcelona-capital/014dca68-1aa8-4b49-b049-13b2a036824f/d"
    },
    {
      "url": "https://www.habitaclia.com/comprar/viviendas/valencia-provincia/valencia-capital/s"
    }
  ],
  "maxItems": 100,
  "scrapeDetails": true,
  "requestDelayMs": 1500,
  "concurrency": 2,
  "maxRunSeconds": 1800,
  "useProxyFallback": true,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

***

### Output Data & Dataset Schema

#### Preview Table

The table below shows sample rows combining the `2026-10-26` Barcelona test fixture structure with illustrative examples to show how fields map across rental and sale listings.

| Listing ID | Title | Price | Currency | Period | Rooms | Baths | Area (m²) | City / District | Agency |
| --- | --- | ---: | --- | --- | ---: | ---: | ---: | --- | --- |
| `014dca68-1aa8-4b49-b049-13b2a036824f` | ¡Vive en el Corazón de Barcelona en este Exclusivo y Luminoso Piso con Terraza! | 5,300 | EUR | month | 5 | 3 | 232 | Barcelona Capital / Les Corts | REVEL |
| `00000000-0000-4000-8000-000000000001` | Bright 3-bedroom flat with terrace (illustrative) | 1,850 | EUR | month | 3 | 2 | 95 | Barcelona / Eixample | Example Agency |
| `00000000-0000-4000-8000-000000000002` | Renovated 4-bedroom family flat (illustrative) | 495,000 | EUR | null | 4 | 2 | 135 | Madrid / Salamanca | Example Estates S.L. |

#### Illustrative JSON Output Example

The JSON record below matches `.actor/dataset_schema.json` using an illustrative listing structure based on the `2026-10-26` Barcelona fixture (private-owner listings output `isPrivateOwner: true`, `phones: []`, and `emails: []`):

```json
{
  "listingId": "014dca68-1aa8-4b49-b049-13b2a036824f",
  "legacyNumericId": "9863004320227",
  "reference": "CA3",
  "title": "¡Vive en el Corazón de Barcelona en este Exclusivo y Luminoso Piso con Terraza!",
  "price": 5300,
  "currency": "EUR",
  "pricePeriod": "month",
  "rooms": 5,
  "baths": 3,
  "area_m2": 232,
  "landArea_m2": null,
  "floor": "SIXTH",
  "constructionYear": 1983,
  "propertyType": "flat",
  "propertySubtype": "flat",
  "propertyStatus": "ALMOST_NEW",
  "operation": "rent",
  "city": "Barcelona Capital",
  "district": "Les Corts",
  "neighborhood": "Pedralbes",
  "province": "Barcelona",
  "address": "Carrer del Capità Arenas 3",
  "zipCode": "08034",
  "lat": 41.3892013,
  "lon": 2.1265986,
  "agency": "REVEL",
  "agent": "Revel",
  "agencyWebsite": "https://agency.example",
  "isPrivateOwner": false,
  "phones": [
    "+34900000000"
  ],
  "emails": [
    "contact@example.com"
  ],
  "energyRating": "F",
  "energyValue": 133,
  "energyEmissionsRating": "F",
  "energyEmissionsValue": 33,
  "features": [
    "ELEVATOR",
    "AIR_CONDITIONER",
    "BALCONY",
    "PRIVATE_PARKING"
  ],
  "photos": [
    "https://images.example.com/habitaclia/photo-1.jpg",
    "https://images.example.com/habitaclia/photo-2.jpg"
  ],
  "description": "Exterior flat with lift, terrace, and clear views in Pedralbes.",
  "url": "https://www.habitaclia.com/alquiler/planta-intermedia/carrer-del-capita-arenas-3/les-corts/barcelona-capital/014dca68-1aa8-4b49-b049-13b2a036824f/d",
  "publicationDate": null,
  "page": 1,
  "position": 1,
  "listUrl": "https://www.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s",
  "tier": "list",
  "scrapedAt": "2026-10-26T00:00:00.000Z"
}
```

#### Full Dataset Field Reference

Every property declared in `.actor/dataset_schema.json` is listed below. Fields may be `null` or omitted when unpublished by the source or when specific to `run-notice` truncation records.

| Field | Type | Tier | Description |
| --- | --- | --- | --- |
| `listingId` | `string \| null` | List, Detail | Stable Habitaclia listing UUID (`raw.id`). Absent on `run-notice` rows. |
| `legacyNumericId` | `string \| null` | List, Detail | Legacy numeric listing ID cast to string when published. |
| `reference` | `string \| null` | List, Detail | Agency or publisher internal reference code when published (e.g. `"CA3"`). |
| `title` | `string \| null` | List, Detail | Public listing headline / title. |
| `price` | `number \| null` | List, Detail | Asking rent or sale price numeric amount. |
| `currency` | `string \| null` | List, Detail | ISO currency code (`"EUR"` is assumed for Spanish listings when the embed omits a currency). |
| `pricePeriod` | `string \| null` | List, Detail | Billing period (`"month"` for `operation: "rent"`; `null` for `operation: "sale"`). |
| `rooms` | `number \| null` | List, Detail | Number of bedrooms/rooms when published. |
| `baths` | `number \| null` | List, Detail | Number of bathrooms when published. |
| `area_m2` | `number \| null` | List, Detail | Built surface area (`builtSurface`) in square metres (`m²`). |
| `landArea_m2` | `number \| null` | List, Detail | Plot/land area (`landArea`) in square metres when published. |
| `floor` | `string \| number \| null` | List, Detail | Floor as a number or published code such as `"THIRD"`, `"SIXTH"`, or `"GROUND"`. |
| `constructionYear` | `number \| null` | List, Detail | Year of construction when published. |
| `propertyType` | `string \| null` | List, Detail | Building type label as published (e.g. `"flat"`, `"house"`). |
| `propertySubtype` | `string \| null` | List, Detail | Property subtype label when published. |
| `propertyStatus` | `string \| null` | List, Detail | Condition/status code when published (e.g. `"ALMOST_NEW"`). |
| `operation` | `string \| null` | List, Detail | Normalized transaction type: `"rent"` or `"sale"` (derived from `transaction.type` or URL path). |
| `city` | `string \| null` | List, Detail | Municipality or city name (e.g. `"Barcelona Capital"`). |
| `district` | `string \| null` | List, Detail | Municipal district name (e.g. `"Les Corts"`, `"Eixample"`). |
| `neighborhood` | `string \| null` | List, Detail | Neighbourhood (`barrio`) name when published (e.g. `"Pedralbes"`). |
| `province` | `string \| null` | List, Detail | Spanish province name (e.g. `"Barcelona"`, `"Madrid"`). |
| `address` | `string \| null` | List, Detail | Display address or street name + number when published. |
| `zipCode` | `string \| null` | List, Detail | Spanish postal code when published. |
| `lat` | `number \| null` | List, Detail | Latitude coordinate when published. |
| `lon` | `number \| null` | List, Detail | Longitude coordinate when published. |
| `agency` | `string \| null` | List, Detail | Real estate agency trade name or publisher name. |
| `agent` | `string \| null` | List, Detail | Public publisher/contact name on the listing. |
| `agencyWebsite` | `string \| null` | List, Detail | Publisher website URL when published. |
| `isPrivateOwner` | `boolean \| null` | List, Detail | `true` when the advertiser is a private individual (`particular`); `false` for commercial agencies. |
| `phones` | `array<string> \| null` | List, Detail | Public commercial phone numbers printed in the embed/description; always `[]` for private owners under Privacy Policy A. |
| `emails` | `array<string> \| null` | List, Detail | Public commercial email addresses printed in the embed/description; always `[]` for private owners. |
| `energyRating` | `string \| null` | List, Detail | Energy consumption efficiency rating letter (`"A"`–`"G"`) when published. |
| `energyValue` | `number \| null` | List, Detail | Energy consumption value (`kWh/m² year`) when published. |
| `energyEmissionsRating` | `string \| null` | List, Detail | CO2 emissions rating letter (`"A"`–`"G"`) when published. |
| `energyEmissionsValue` | `number \| null` | List, Detail | CO2 emissions numeric value (`kg CO2/m² year`) when published. |
| `features` | `array<string> \| null` | List, Detail | Published amenity/feature codes (e.g. `"ELEVATOR"`, `"TERRACE"`, `"AIR_CONDITIONER"`). |
| `photos` | `array<string> \| null` | List, Detail | Public photo URLs extracted from listing multimedia metadata. |
| `description` | `string \| null` | List, Detail | Plain-text listing description when published. |
| `url` | `string \| null` | List, Detail | Canonical public Habitaclia listing detail URL (`…/{uuid}/d`). |
| `publicationDate` | `string \| null` | List, Detail | Publication timestamp when exposed; current Habitaclia embeds omit it, so this field is normally `null`. |
| `page` | `integer \| null` | List, Detail (from list) | Search results page number where the listing was found; `null` for direct detail seeds. |
| `position` | `integer \| null` | List, Detail (from list) | One-based position of the listing on its search results page; `null` for direct detail seeds. |
| `listUrl` | `string \| null` | List, Detail | Search URL where the listing was discovered, or the direct detail URL for detail seeds. |
| `tier` | `string \| null` | List, Detail | Extraction tier: `"list"` for a search-card row or `"detail"` when merged with a fetched detail page. |
| `scrapedAt` | `string \| null` | List, Detail | ISO 8601 UTC timestamp recording when the row was scraped. |
| `detailError` | `string \| null` | List (fallback) | Present only when `scrapeDetails: true` failed for that listing and the list row was preserved at the `listing` rate. |
| `recordType` | `string \| null` | Run-notice | Set to `"run-notice"` on the single uncharged truncation notice; omitted on listing rows. |
| `truncatedAfter` | `integer \| null` | Run-notice | Total number of charged listing rows saved before the truncated run stopped. |
| `reason` | `string \| null` | Run-notice | Stop reason copied from `OUTPUT.stopReason` (`"maxItems"`, `"max-charge-reached"`, `"run-time-limit"`, `"proxy-budget"`, `"cloudflare-challenge"`, `"empty-page"`, or `"errors"`). |

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

- **Dataset Views**: Includes a pre-configured **Overview** (`overview`) table in Apify Console displaying `listingId`, `title`, `price`, `currency`, `operation`, `rooms`, `baths`, `area_m2`, `city`, `neighborhood`, `agency`, `tier`, and clickable `url`. Export cleanly to JSON, CSV, Excel, XML, or Parquet.
- **Key-Value Store — `OUTPUT`**: Every run writes a full JSON summary under key `OUTPUT` containing normalized input, pricing events, seed statuses, `siteTotalEntries`, `pushed` counts, `listSource`, `unavailableFields`, `http` stats, `robots` stats, `robotsDisallowedHits`, `errors`, `stopReason`, and `truncated`.

***

### Pricing & Apify Store Tier Discounts

This Actor uses **Pay-Per-Event (PPE)** billing in **USD** (live pricing verified `2026-11-21`) with **no run-start fee** (`$0.00`). Apify Store subscription plans automatically apply **5% to 15% tier discounts** on every event:

| Event | Description | Free | Bronze (5% off) | Silver (10% off) | Gold (15% off) | Platinum (15% off) | Diamond (15% off) |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |
| `listing` | One Habitaclia.com listing from a public search page | `$0.0005` (`$0.50`/1k) | `$0.000475` (`$0.475`/1k) | `$0.00045` (`$0.45`/1k) | `$0.000425` (`$0.425`/1k) | `$0.000425` (`$0.425`/1k) | `$0.000425` (`$0.425`/1k) |
| `listing-detail` | One listing confirmed from its detail page (replaces `listing`) | `$0.0005` (`$0.50`/1k) | `$0.000475` (`$0.475`/1k) | `$0.00045` (`$0.45`/1k) | `$0.000425` (`$0.425`/1k) | `$0.000425` (`$0.425`/1k) | `$0.000425` (`$0.425`/1k) |

#### Cost Comparison & Billing Guarantees

- **~50% lower cost vs. benchmark**: On the Free tier, 1,000 Habitaclia listings cost **$0.50** (**$0.425** on Gold/Platinum/Diamond) with **$0.00** start fee—half the **$1.00005** per 1,000 results benchmark of `trev0n` (`$0.001` × 1,000 + `$0.00005` start fee).
- **No double-charging on details**: `listing-detail` **replaces** `listing` for that row; the two events are never charged together on a single listing.
- **Graceful detail fallback**: If a detail page fails while `scrapeDetails: true`, the Actor keeps the list row (with `detailError`) and charges only `listing`.
- **Zero charge on non-results**: Deduplicated listings, uncharged `run-notice` rows, and failed runs with zero scraped listings incur **$0.00** in event charges.
- Always check the live **Pricing** tab in Apify Console for any separately billed platform compute or storage usage.

***

### API & SDK Quickstart

Call **Habitaclia.com Real Estate Scraper** (`Stone_JadeX/habitaclia-com-scraper`) programmatically from JavaScript or Python using the official Apify API client libraries.

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

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

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

const run = await client.actor('Stone_JadeX/habitaclia-com-scraper').call({
    startUrls: [
        { url: 'https://www.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s' },
        { url: 'https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s' },
    ],
    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.length} listings`);
for (const item of listings.slice(0, 5)) {
    console.log(item.listingId, item.title, item.price, item.currency, `${item.area_m2} m2`);
}
```

#### Python — `ApifyClient`

```python
import os
from apify_client import ApifyClient

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

run = client.actor("Stone_JadeX/habitaclia-com-scraper").call(run_input={
    "startUrls": [
        {"url": "https://www.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s"},
        {"url": "https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s"},
    ],
    "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(f"Collected {len(items)} listings")
for item in items[:5]:
    print(item.get("listingId"), item.get("title"), item.get("price"), item.get("currency"), item.get("city"))
```

***

### FAQ, Compliance & Limitations

#### Is it legal to scrape Habitaclia.com?

This Actor reads only publicly available listing pages and the public `window.__INITIAL_PROPS__` JSON payload served in a normal browser session, without logging in or bypassing access controls. To protect personal privacy, phone numbers and email addresses belonging to private owners (`isPrivateOwner: true`) are automatically stripped, retaining only publicly published commercial contacts of real estate agencies. You are responsible for ensuring your downstream use complies with applicable law (including GDPR) and Habitaclia's terms of use. This is an independent tool and is not affiliated with Habitaclia.

#### How does the Actor handle `robots.txt` and login/account pages?

At startup, the Actor fetches `https://www.habitaclia.com/robots.txt`, parses `User-agent: *` rules scoped to `www.habitaclia.com`, and honors any `Crawl-delay` value higher than `requestDelayMs`. Standard search list paths (`/s` and `/s/N`) and detail pages (`/…/{uuid}/d`) are parsed without calling disallowed phone-reveal, AJAX, or captcha endpoints (`/solicitud/vertelefono*`, `/phone-validation*`). If a requested URL matches a Disallow rule, it is still requested, logged as a warning and counted in `robotsDisallowedHits`. Login and account URLs are always refused and never requested.

#### How do proxy fallback and the 5 MB residential cap work?

Direct connections (`proxyConfiguration.useApifyProxy: false`) are used by default, and residential proxies should never be configured as a default. When an Apify Proxy group is provided:

- Enable `useProxyFallback: true` to stay on direct connections until repeated HTTP `403` or `429` responses trigger fallback.
- When a `RESIDENTIAL` proxy group is used, proxy transfer is hard-capped at **5 MB per run** (not user-configurable). If the projected next request would exceed 5 MB, the run stops cleanly with `stopReason: "proxy-budget"`.
- Detail requests remain on direct connections by default when a residential proxy group is configured unless `allowDetailOnResidential: true` is explicitly turned on.

#### What are the main limitations?

- **Habitaclia.com only**: Input validation restricts `startUrls` strictly to public `habitaclia.com` search (`/…/s`, `/…/s/N`) and detail (`/…/{uuid}/d`) URLs.
- **Ceiling vs. guarantee**: `maxItems` defaults to `50` and is capped at `2,000` (matching `maxPages` and `startPage`). Actual output depends on live search inventory and site availability.
- **Source-omitted metadata**: Habitaclia embeds often omit `transaction.price.currency` (assumed `"EUR"` for Spanish listings) and do not expose a stable `publicationDate` field (left `null` when unpublished).
- **Anti-bot & snapshot semantics**: Cloudflare challenges (`HTTP 403`) stop the run cleanly with `stopReason: "cloudflare-challenge"`. Each run provides a point-in-time snapshot rather than live monitoring.

***

### Changelog

#### 0.1.1 — 2026-11-21

- Added explicit `prefill` defaults (`startUrls`, `maxItems`, `startPage`, `scrapeDetails`, `requestDelayMs`, `concurrency`, `maxRunSeconds`, `useProxyFallback`, `allowDetailOnResidential`) and organized `.actor/input_schema.json` into clear `sectionCaption` groups.
- Upgraded `README.md` to full Store documentation with complete 11-parameter input table + 2 JSON examples, illustrative JSON output, full 49-field dataset reference, live Pay-Per-Event pricing with Apify Store subscription tier discounts (Bronze through Diamond), JavaScript & Python `ApifyClient` SDK quickstarts, and aligned `robots.txt` warn-only compliance wording.

#### 0.1.0 — 2026-10-26

- Initial Habitaclia.com real estate scraper supporting list and optional detail tiers via `window.__INITIAL_PROPS__`, `/s` and `/s/N` pagination, Privacy Policy A contact filtering, fixed 5 MB residential proxy safety cap, and flat `$0.0005` PPE pricing with zero start fee.

# Changelog

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

# Actor input Schema

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

Optional. A Habitaclia search URL such as https://www.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s, or a listing URL ending in /{uuid}/d. Empty input uses Barcelona + Madrid rentals (viviendas).

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

Stop after this many listings.

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

Optional. Each search page has about 29 listings. Pages use /s (page 1) and /s/N (page >=2).

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

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

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

Re-fetches the public detail page. List cards already carry description, energy, photos, and public contacts from **INITIAL_PROPS**; use this when you want to confirm the detail embed. 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.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s"
    },
    {
      "url": "https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s"
    }
  ],
  "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`):

Public listing rows from the default dataset, including any run-notice row. Fields depend on the input, the list or detail tier, and source availability.

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

Run statistics, errors, stop reason, normalized input, and the pricing used. Written to the OUTPUT key even when input validation fails or a run is truncated.

# 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.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s"
        },
        {
            "url": "https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s"
        }
    ],
    "maxItems": 50,
    "startPage": 1,
    "scrapeDetails": false,
    "requestDelayMs": 1200,
    "concurrency": 1,
    "maxRunSeconds": 3600,
    "useProxyFallback": false,
    "allowDetailOnResidential": false
};

// Run the Actor and wait for it to finish
const run = await client.actor("stone_jadex/habitaclia-com-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.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s" },
        { "url": "https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s" },
    ],
    "maxItems": 50,
    "startPage": 1,
    "scrapeDetails": False,
    "requestDelayMs": 1200,
    "concurrency": 1,
    "maxRunSeconds": 3600,
    "useProxyFallback": False,
    "allowDetailOnResidential": False,
}

# Run the Actor and wait for it to finish
run = client.actor("stone_jadex/habitaclia-com-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.habitaclia.com/alquiler/viviendas/barcelona-provincia/barcelona-capital/s"
    },
    {
      "url": "https://www.habitaclia.com/alquiler/viviendas/madrid-provincia/madrid-capital/s"
    }
  ],
  "maxItems": 50,
  "startPage": 1,
  "scrapeDetails": false,
  "requestDelayMs": 1200,
  "concurrency": 1,
  "maxRunSeconds": 3600,
  "useProxyFallback": false,
  "allowDetailOnResidential": false
}' |
apify call stone_jadex/habitaclia-com-scraper --silent --output-dataset

```

## MCP server setup

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