# Foreclosure Auctions Scraper (Germany ZVG & Japan Akiya) (`vesper_studio/foreclosure-real-estate-auctions`) Actor

Extract official judicial real estate foreclosure auctions in Germany (zvg-portal.de, 16 Länder) and Japan (bit.courts.go.jp, 47 prefectures / akiya). Parses court Gutachten & 3点セット PDFs via PyMuPDF for market valuation, minimum bid, m², occupancy, and optional BYOK LLM risk flags.

- **URL**: https://apify.com/vesper_studio/foreclosure-real-estate-auctions.md
- **Developed by:** [Xavier Richard](https://apify.com/vesper_studio) (community)
- **Categories:** Real estate, Lead generation, Business
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 foreclosure auction lot extracteds

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

## Foreclosure & Judicial Real Estate Auctions (`zvg-portal.de` + `bit.courts.go.jp`)

Extract official judicial real estate foreclosure auctions in **Germany** (`zvg-portal.de`, all 16 Bundesländer) and **Japan** (`www.bit.courts.go.jp`, all 47 prefectures / *akiya* & urban properties), turning complex stateful court portals and legal PDF appraisals (*Gutachten* / *Bekanntmachung* in DE, *3点セット* in JP) into clean, structured JSON for investors, *marchands de biens*, and real-estate analysts.

### Key Features

- **Zero Browser, Zero Proxy, 512 MB Memory Footprint**: Pure async `httpx` with stateful cookie persistence, multi-encoding decoding (`UTF-8`, `ISO-8859-1`, `Shift-JIS` / `CP932`), and `selectolax` (`lexbor`) HTML parsing.
- **Germany (`zvg_de`)**: Queries all 16 *Bundesländer* (`bw`, `by`, `be`, `br`, `hb`, `hh`, `he`, `mv`, `ni`, `nw`, `rp`, `sl`, `sn`, `st`, `sh`, `th`), navigates `blaettern` pagination, skips cancelled hearings (*aufgehoben*) by default, extracts *Aktenzeichen*, *Amtsgericht*, *Grundbuch*, *Verkehrswert*, *Termin*, and downloads *Gutachten* & *Amtliche Bekanntmachung* PDFs with proper `Referer` headers.
- **Japan (`bit_jp`)**: Supports all 47 Japanese prefectures (plus Hokkaido's 4 court districts `91`–`94`), executes the multi-step BIT form workflow (`pk001/h02` → `ps002/h04` → `ps002/h05` → `pr001/h03` → `pr001/h05`), converts Wareki dates (`令和08年12月15日` → `2026-12-15`), extracts *売却基準価額* (market value), *買受可能価額* (minimum bid), *買受申出保証金* (deposit), floor/land m², coordinates, and *3点セット* PDF links.
- **High-Precision PyMuPDF Legal PDF Extraction (`parsePdfDetails`)**: Extracts *Verkehrswert* / *売却基準価額*, *Mindestgebot* / *買受可能価額*, `§ 74a / § 85a ZVG` *Wertgrenzen weggefallen* flags, surface areas (m²), construction year, occupancy/tenancy status (*vermietet*, *eigengenutzt*, *Leerstand*, *占有者*), monthly rent, and legal risk flags (*Denkmalschutz*, *Altlasten*, *Nießbrauch*, *再建築不可*, *共有持分*, etc.). Detects scanned image-only PDFs cleanly (`pdf_is_scanned: true`).
- **Polite Rate Limiting**: Per-host async throttling (`requestDelaySec`, default `1.0s` + jitter) and exponential backoff retries to avoid overloading judicial servers.
- **Optional BYOK LLM Risk Summary (`llmApiKey`)**: Optionally pass your own OpenAI, Google Gemini, or Anthropic API key (`llmProvider`: `auto`, `openai`, `gemini`, `anthropic`) to generate a structured risk & due-diligence summary (`llm_risk_summary`). Never required.
- **Delta Mode (`onlyNew`) + Graceful Abort**: Persists seen judicial lot IDs across scheduled runs in a named Apify Key-Value Store (`foreclosure-real-estate-auctions-seen` / key `seen_auction_lots`), avoids detail/PDF HTTP fetches for already-seen lots, and checkpoints on `Event.ABORTING`.
- **Pay-Per-Event Pricing**:
  - `auction-lot` (**$0.005 / lot**): Charged once per delivered, deduplicated judicial auction record matching your filters.
  - `pdf-parsed` (**$0.01 / PDF**): Charged only when `parsePdfDetails` is enabled and an official *Gutachten*, *Bekanntmachung*, or *3点セット* PDF is downloaded and parsed via PyMuPDF.
- **High-Throughput Optimizations**: Concurrent DE & JP source execution (`zvg_de` || `bit_jp`), single-request `zvg-portal.de` fetch (`&all=1`), pre-detail card filtering, and offloaded PyMuPDF parsing (`asyncio.to_thread`).

### Input Configuration

| Field | Type | Default | Description |
|---|---|---|---|
| `sources` | array | `["zvg_de", "bit_jp"]` | Portals to query (`zvg_de`, `bit_jp`). |
| `deStates` | array | `["be"]` | German state codes (`land_abk`). Empty = all 16 Länder. |
| `jpPrefectures` | array | `["13"]` | Japanese JIS codes (`13`, `27`), names (`Tokyo`, `大阪府`), or `ALL`. |
| `propertyTypes` | array | `[]` | Filter: `residential_house`, `apartment`, `commercial_mixed`, `land`, `garage_other`. |
| `minMarketValue` | number | `0` | Minimum appraised value in local currency (EUR / JPY). |
| `maxMarketValue` | number | `0` | Maximum appraised value in local currency (`0` = unlimited). |
| `parsePdfDetails` | boolean | `true` | Download & parse official PDFs with PyMuPDF. |
| `maxPdfPages` | integer | `20` | Page cap per PDF to stay under 512 MB RAM. |
| `includeCancelled` | boolean | `false` | Include cancelled/withdrawn auctions. |
| `llmApiKey` | string | `null` | Optional BYOK API key (OpenAI / Gemini / Anthropic). |
| `llmProvider` | string | `"auto"` | `auto`, `openai`, `gemini`, or `anthropic`. |
| `onlyNew` | boolean | `false` | Delta mode via KV Store (`seen_auction_lots`). |
| `requestDelaySec` | number | `1.0` | Polite delay per host in seconds. |
| `maxItems` | integer | `20` | Maximum lots to deliver across selected sources. |

### Output Schema (Sample Fields)

Each item pushed to the default dataset follows `.actor/dataset_schema.json`:

- `source`, `lot_id`, `country`, `state_or_prefecture`, `court_name`, `case_number`
- `property_type`, `property_type_raw`, `title`, `address`, `postal_code`, `city`, `latitude`, `longitude`
- `currency` (`EUR` / `JPY`), `market_value`, `minimum_bid`, `minimum_bid_ratio`, `deposit_amount`, `wertgrenzen_dropped`
- `auction_date`, `auction_datetime`, `bidding_period`, `sale_decision_date`
- `land_area_sqm`, `building_area_sqm`, `construction_year`, `occupancy_status`, `occupancy_rate_pct`, `monthly_rent`
- `risk_flags`, `pdf_urls`, `pdf_parsed`, `pdf_is_scanned`, `llm_risk_summary`

### Local Development & Verification

```bash
python -m pytest -v
```

# Actor input Schema

## `sources` (type: `array`):

Select which official judicial auction portals to scrape: Germany (zvg-portal.de) and/or Japan (www.bit.courts.go.jp).

## `deStates` (type: `array`):

German federal state codes (`land_abk`): bw, by, be, br, hb, hh, he, mv, ni, nw, rp, sl, sn, st, sh, th. Leave empty to scan all 16 Länder when `zvg_de` is enabled.

## `jpPrefectures` (type: `array`):

Japanese prefecture codes (e.g. '13' Tokyo, '27' Osaka, '14' Kanagawa, '26' Kyoto, '01'/'91'-'94' Hokkaido, '40' Fukuoka) or prefecture names in English/Japanese (e.g. 'Tokyo', '大阪府'). Leave empty to scan Tokyo ('13') by default, or use 'ALL' to scan all 47 prefectures.

## `propertyTypes` (type: `array`):

Optional normalized property category filter: residential_house, apartment, commercial_mixed, land, garage_other. Leave empty for all property types.

## `minMarketValue` (type: `number`):

Optional minimum appraised value (Verkehrswert in EUR or 売却基準価額 in JPY).

## `maxMarketValue` (type: `number`):

Optional maximum appraised value (0 = no upper limit).

## `parsePdfDetails` (type: `boolean`):

When enabled, downloads official PDF attachments and parses text with PyMuPDF to extract surface area, construction year, tenancy/occupancy status, minimum bid / Wertgrenzen (§ 74a/§ 85a ZVG), and legal risk flags. Each parsed PDF bills one 'pdf-parsed' event.

## `maxPdfPages` (type: `integer`):

Caps PyMuPDF page parsing per document (keeps memory < 512 MB on 100+ page Gutachten).

## `includeCancelled` (type: `boolean`):

Include listings marked as cancelled/withdrawn (Termin aufgehoben / 中止).

## `llmApiKey` (type: `string`):

Optional Bring-Your-Own-Key API key. When provided, sends the extracted Gutachten / 3点セット text (or HTML summary for scanned PDFs) to your chosen LLM to produce a structured risk & anomaly analysis. Never required.

## `llmProvider` (type: `string`):

LLM provider for optional risk summary (auto-detected from key prefix if set to 'auto').

## `llmModel` (type: `string`):

Optional model name (defaults: gpt-4o-mini, gemini-2.5-flash, claude-3-5-haiku-latest).

## `onlyNew` (type: `boolean`):

Skip court cases already delivered in previous runs using the persistent named Apify Key-Value Store ('foreclosure-real-estate-auctions-seen' / 'seen_auction_lots'). Checkpoints on completion and graceful abort.

## `requestDelaySec` (type: `number`):

Minimum delay between consecutive HTTP requests to the same judicial server.

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

Maximum number of auction lots to deliver across all selected sources. Each delivered lot bills one 'auction-lot' event.

## Actor input object example

```json
{
  "sources": [
    "zvg_de",
    "bit_jp"
  ],
  "deStates": [
    "be"
  ],
  "jpPrefectures": [
    "13"
  ],
  "propertyTypes": [],
  "minMarketValue": 0,
  "maxMarketValue": 0,
  "parsePdfDetails": true,
  "maxPdfPages": 20,
  "includeCancelled": false,
  "llmProvider": "auto",
  "onlyNew": false,
  "requestDelaySec": 0.4,
  "maxItems": 20
}
```

# Actor output Schema

## `lots` (type: `string`):

No description

# API

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

## JavaScript example

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

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

// Prepare Actor input
const input = {
    "sources": [
        "zvg_de",
        "bit_jp"
    ],
    "deStates": [
        "be"
    ],
    "jpPrefectures": [
        "13"
    ],
    "parsePdfDetails": true,
    "maxPdfPages": 20,
    "includeCancelled": false,
    "onlyNew": false,
    "requestDelaySec": 0.4,
    "maxItems": 20
};

// Run the Actor and wait for it to finish
const run = await client.actor("vesper_studio/foreclosure-real-estate-auctions").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 = {
    "sources": [
        "zvg_de",
        "bit_jp",
    ],
    "deStates": ["be"],
    "jpPrefectures": ["13"],
    "parsePdfDetails": True,
    "maxPdfPages": 20,
    "includeCancelled": False,
    "onlyNew": False,
    "requestDelaySec": 0.4,
    "maxItems": 20,
}

# Run the Actor and wait for it to finish
run = client.actor("vesper_studio/foreclosure-real-estate-auctions").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 '{
  "sources": [
    "zvg_de",
    "bit_jp"
  ],
  "deStates": [
    "be"
  ],
  "jpPrefectures": [
    "13"
  ],
  "parsePdfDetails": true,
  "maxPdfPages": 20,
  "includeCancelled": false,
  "onlyNew": false,
  "requestDelaySec": 0.4,
  "maxItems": 20
}' |
apify call vesper_studio/foreclosure-real-estate-auctions --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,vesper_studio/foreclosure-real-estate-auctions"
        }
    }
}
```

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/S7v83bvF62VWDL3iN/builds/IVJRB8LFH1o9Pgaw5/openapi.json
