# Page2JSON — Dynamic Webpage to Structured JSON (`mibedk/page2json-dynamic-extraction`) Actor

Convert public webpages into clean structured JSON, including JavaScript-rendered pages. Built for agents, automations, and data workflows.

- **URL**: https://apify.com/mibedk/page2json-dynamic-extraction.md
- **Developed by:** [Mikkel Bech-Hansen](https://apify.com/mibedk) (community)
- **Categories:** Developer tools, Other, Automation
- **Stats:** 1 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.36 / 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/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js/docs.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python/docs.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## Page2JSON Actor

Convert public webpages into clean structured JSON, including JavaScript-rendered pages.

### Features

- **Multi-mode extraction**: auto, static, browser, network, screenshot
- **Intelligent content detection**: JSON-LD, embedded JSON, network responses, HTML scraping
- **Browser rendering**: Full Chromium with auto-scroll, element waiting, and network capture
- **Dynamic content handling**: Handles SPAs, lazy-loaded content, and JavaScript-rendered pages
- **Structured JSON output**: Maps extracted data to custom schemas

### Getting Started

#### Prerequisites

- Node.js 20+
- Apify CLI

#### Installation

```bash
## Install Apify CLI globally
npm install -g apify-cli

## Initialize the actor
apify init page2json-actor --yes

## Install dependencies
npm install

## Build and push
npm run build

## Run locally
apify run

## Run on Apify platform
apify push
````

### Input Schema

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `urls` | array | required | List of URLs to extract content from |
| `schema` | object | optional | Desired JSON schema for extracted data |
| `mode` | string | 'auto' | Extraction mode: auto, static, browser, network, screenshot |
| `render.waitForSelector` | string | optional | CSS selector to wait for before extracting |
| `render.waitForNetworkIdle` | boolean | true | Wait for network to be idle before extracting |
| `render.maxWaitMs` | integer | 15000 | Maximum wait time (milliseconds) |
| `render.scroll` | boolean | false | Enable scrolling for lazy-loaded content |
| `render.maxScrolls` | integer | 8 | Maximum scrolls to perform |
| `render.scrollDelayMs` | integer | 800 | Delay between scrolls (milliseconds) |
| `render.clickSelectors` | array | \[] | CSS selectors to click before extraction |
| `extraction.preferJsonLd` | boolean | true | Prefer data from JSON-LD |
| `extraction.preferEmbeddedJson` | boolean | true | Prefer embedded JSON (e.g., **NEXT\_DATA**) |
| `extraction.preferNetworkJson` | boolean | true | Prefer network JSON responses |
| `extraction.includeRawText` | boolean | false | Include raw page text in output |
| `extraction.includeHtml` | boolean | false | Include raw HTML in output |
| `extraction.includeScreenshot` | boolean | false | Include a screenshot in output |
| `limits.maxPages` | integer | 10 | Maximum pages to process |
| `limits.maxConcurrency` | integer | 3 | Maximum concurrent requests |
| `limits.maxResponseBytes` | integer | 5000000 | Maximum response size (bytes) |

### Output

Each URL returns a structured result:

| Field | Type | Description |
|-------|------|-------------|
| `url` | string | The processed URL |
| `status` | string | success, partial\_success, failed, blocked, timeout, invalid\_input, unsupported\_content\_type |
| `extractionMethod` | string | How the data was extracted (static\_html, json\_ld, embedded\_json, browser\_dom, browser\_network\_json) |
| `rendered` | boolean | Whether browser rendering was used |
| `confidence` | number | Extraction quality score (0.0 - 1.0) |
| `data` | object | Extracted data mapped to the schema |
| `missingFields` | array<string> | Fields that were requested but not found |
| `warnings` | array<string> | Issues encountered during extraction |
| `costSignals` | object | Usage metrics for billing estimation |
| `debug` | object | Technical details for troubleshooting |

### Cost Model

| Method | Cost |
|--------|------|
| Static HTML | $0.001 |
| JSON-LD / Embedded JSON | $0.005 |
| Network JSON | $0.01 |
| Full Rendering | $0.02 |
| Screenshot | +$0.01 |

### Examples

#### Simple extraction (auto mode)

```json
{
  "urls": ["https://example.com"],
  "schema": {
    "title": "string",
    "content": "string"
  }
}
```

#### Product page extraction

```json
{
  "urls": ["https://shop.example.com/product/123"],
  "schema": {
    "title": "string",
    "price": "string",
    "description": "string",
    "images": "array",
    "reviews": "array"
  },
  "mode": "auto"
}
```

#### Browser-rendered page (SPA)

```json
{
  "urls": ["https://react-app.example.com"],
  "schema": {
    "products": "array"
  },
  "mode": "browser",
  "render": {
    "waitForSelector": ".product-grid",
    "scroll": true,
    "maxScrolls": 10,
    "clickSelectors": ["#load-more-button"]
  }
}
```

### Architecture

```
src/
  extractors/
    staticHtmlExtractor.ts  — HTML scraping (beautifulsoup4)
    jsonLdExtractor.ts       — JSON-LD extraction (jsonld npm)
    embeddedJsonExtractor.ts — __NEXT_DATA__ etc. (regex)
    browserDomExtractor.ts   — DOM scraping (playwright)
    networkJsonExtractor.ts  — Intercept network calls (playwright)
    tableExtractor.ts        — HTML table parsing (cheerio)
    commonFieldExtractors.ts — Title, meta, headings, links
  browser/
    renderPage.ts            — Playwright browser control
    captureNetworkJson.ts    — Network response monitoring
    waitForDomStable.ts      — DOM stability detection
    autoScroll.ts            — Lazy content loading
  scoring/
    confidence.ts            — Quality scoring (0.0 - 1.0)
    dynamicDetection.ts      — Detect if browser is needed
  schema/
    validateInput.ts         — Input validation
    mapToSchema.ts           — Schema mapping
  monetization/
    billingEstimator.ts      — Cost estimation
    usageLogger.ts           — Usage logging
  utils/
    htmlProcessor.ts         — Text extraction
    retryLogic.ts            — Retry with backoff
    errorHandling.ts         — Error classes
    rateLimiter.ts           — Concurrency control
  types.ts                   — TypeScript types
  main.ts                    — Actor entry point
```

### Running Locally

```bash
## Build
npm run build

## Run locally
apify run

## Run on Apify
apify push
```

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `APIFY_TOKEN` | — | Apify API token |
| `APIFY_DEFAULT_KEY_VALUE_STORE_ID` | actor's default | Key-value store ID |
| `PLAYWRIGHT_TIMEOUT` | 30000 | Playwright browser timeout (ms) |
| `MAX_BROWSERS` | 5 | Max concurrent browsers |

### API Reference

#### Input

```typescript
interface Page2JSONInput {
  urls: string[];
  schema?: Record<string, string>;
  mode?: 'auto' | 'static' | 'browser' | 'network' | 'screenshot';
  render?: {
    waitForSelector?: string;
    waitForNetworkIdle?: boolean;
    maxWaitMs?: number;
    scroll?: boolean;
    maxScrolls?: number;
    scrollDelayMs?: number;
    clickSelectors?: string[];
  };
  extraction?: {
    preferJsonLd?: boolean;
    preferEmbeddedJson?: boolean;
    preferNetworkJson?: boolean;
    includeRawText?: boolean;
    includeHtml?: boolean;
    includeScreenshot?: boolean;
  };
  limits?: {
    maxPages?: number;
    maxConcurrency?: number;
    maxResponseBytes?: number;
  };
}
```

#### Output

```typescript
interface ExtractionResult {
  url: string;
  status: 'success' | 'partial_success' | 'failed' | 'blocked' | 'timeout' | 'invalid_input' | 'unsupported_content_type';
  extractionMethod: string;
  rendered: boolean;
  confidence: number;
  data: Record<string, unknown>;
  missingFields: string[];
  warnings: string[];
  costSignals: {
    browserUsed: boolean;
    requestCount: number;
    durationMs: number;
    responseBytes: number;
    totalCost: number;
  };
  debug: {
    staticTextLength: number;
    renderedTextLength: number;
    jsonLdFound: boolean;
    embeddedJsonFound: boolean;
    networkJsonCandidates: number;
  };
}
```

### Contributing

Contributions are welcome! Please open an issue or submit a pull request.

### License

MIT

# Actor input Schema

## `urls` (type: `array`):

List of URLs to extract content from.

## `schema` (type: `object`):

JSON schema defining the desired output structure.

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

Extraction mode (auto, static, browser, network, or screenshot).

## `render` (type: `object`):

Browser rendering options for dynamic pages.

## `extraction` (type: `object`):

Data extraction preferences.

## `limits` (type: `object`):

Request and processing limits.

## Actor input object example

```json
{}
```

# 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("mibedk/page2json-dynamic-extraction").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("mibedk/page2json-dynamic-extraction").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).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 mibedk/page2json-dynamic-extraction --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=mibedk/page2json-dynamic-extraction",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Page2JSON — Dynamic Webpage to Structured JSON",
        "description": "Convert public webpages into clean structured JSON, including JavaScript-rendered pages. Built for agents, automations, and data workflows.",
        "version": "0.1",
        "x-build-id": "xZfaHXRSWjRNBacll"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/mibedk~page2json-dynamic-extraction/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-mibedk-page2json-dynamic-extraction",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/mibedk~page2json-dynamic-extraction/runs": {
            "post": {
                "operationId": "runs-sync-mibedk-page2json-dynamic-extraction",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/mibedk~page2json-dynamic-extraction/run-sync": {
            "post": {
                "operationId": "run-sync-mibedk-page2json-dynamic-extraction",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "urls"
                ],
                "properties": {
                    "urls": {
                        "title": "URLs",
                        "type": "array",
                        "description": "List of URLs to extract content from.",
                        "items": {
                            "type": "string"
                        }
                    },
                    "schema": {
                        "title": "Schema",
                        "type": "object",
                        "description": "JSON schema defining the desired output structure."
                    },
                    "mode": {
                        "title": "Mode",
                        "enum": [
                            "auto",
                            "static",
                            "browser",
                            "network",
                            "screenshot"
                        ],
                        "type": "string",
                        "description": "Extraction mode (auto, static, browser, network, or screenshot)."
                    },
                    "render": {
                        "title": "Render Options",
                        "type": "object",
                        "description": "Browser rendering options for dynamic pages."
                    },
                    "extraction": {
                        "title": "Extraction",
                        "type": "object",
                        "description": "Data extraction preferences."
                    },
                    "limits": {
                        "title": "Limits",
                        "type": "object",
                        "description": "Request and processing limits."
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
