# HTML Table Extractor: Web Tables to CSV, JSON, Excel (`ucchiii/html-table-extractor`) Actor

Extract HTML tables from web pages or raw HTML into JSON rows keyed by header, with optional CSV and Excel files: colspan/rowspan, header detection, number cleanup, robots.txt respected. Empty input = free demo. Failed pages are free.

- **URL**: https://apify.com/ucchiii/html-table-extractor.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** Developer tools, Automation, Other
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.47 / 1,000 extracted tables

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

**Turns the tables on web pages into clean rows (and CSV or Excel files), one dataset row per table row.** Built for analysts, researchers and developers who need the data from an HTML table (a Wikipedia list, a price page, a standings table, a report) in a spreadsheet or a database, and are tired of copy-pasting, broken merged cells and header rows that come out as data. Plain HTTP, no browser, no login, no API key.

**Try it free: leave input empty and press Start.** The demo extracts two tables from a bundled sample page (one with a two-row header and merged cells) and is not charged (rows carry `_demo: true`).

| Region | Revenue Q1 | Revenue Q2 | \_sourceUrl | \_tableIndex | \_rowIndex |
|---|---|---|---|---|---|
| North | $1,200.50 | $1,450.00 | https://example.com/sample-report | 0 | 0 |
| South | $980.00 | $1,010.25 | https://example.com/sample-report | 0 | 1 |

### What you get

- **One dataset row per table row**, keyed by the column header, plus `_sourceUrl`, `_tableIndex` and `_rowIndex` (all 0-based; the header row is not counted)
- **Header detection**: `thead` or leading `th` rows; multi-row headers are merged (`Revenue Q1`); empty names become `column_N`, duplicates get a `_2` suffix; or force first-row / no header
- **colspan and rowspan** expanded, so every row is complete (the merged value is repeated, or left empty if you prefer)
- **Number cleanup** (optional): `$1,234.50` becomes `1234.5`, `12%` becomes `12`, `(5)` becomes `-5`; text, dates and IDs with leading zeros stay as they are
- **Pick tables**: CSS selector (`table.wikitable`, `#prices`), table indexes, minimum row count, maximum tables per page
- **CSV and Excel files** (optional): one file per table in the key-value store; the `TABLES` record lists the keys, columns and row counts
- Inputs: page URLs, raw HTML strings, or both in one run
- Footnote marks such as `[1]` on Wikipedia are dropped from cell text

### Polite by design

Only the URLs you give are fetched (no crawling, no login, no JavaScript, no proxy tricks). **robots.txt is respected by default** (disallowed pages are skipped and free). One request at a time per host, at least 1 second apart, retries with backoff (1, 2, 4 seconds, or the server's Retry-After) for timeouts, 429 and 502/503/504. The User-Agent identifies a generic bot. Internal and private addresses are refused. Pages over 5 MB are refused.

### Price

**$0.0067 per run with results, plus $0.67 per 1,000 tables** ($0.00067 per table extracted, whatever its number of rows). One run with 1 table costs $0.00737; a run with 1,000 tables costs $0.6767.
The run fee is charged once, together with the first extracted table. Failed fetches, pages blocked by robots.txt, pages without tables and the demo are free, and a run where nothing is extracted costs nothing.
Set a maximum cost per run to cap spend: when it is reached the run stops cleanly (status Succeeded) and `STATS` says so (`stoppedAtChargeLimit: true`).

### Input

| Field | What it does |
|---|---|
| `urls` | Page URLs with tables |
| `htmlStrings`, `baseUrl` | Raw HTML (and the label written to `_sourceUrl`) |
| `tableSelector`, `tableIndexes` | Which tables to keep |
| `minRows`, `maxTablesPerPage` | Skip tiny tables; cap tables (and cost) per page |
| `headerMode` | `auto`, `first_row`, `none` |
| `fillSpans` | Repeat merged cells (default on) |
| `numericCleanup` | Convert numbers (default off) |
| `saveCsv`, `saveXlsx` | Save each table as a file |
| `respectRobotsTxt` | Default on |
| `maxRetries`, `timeoutSecs`, `concurrency`, `userAgent` | Fetching options |

Example input:

```json
{
  "urls": ["https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"],
  "tableSelector": "table.wikitable",
  "maxTablesPerPage": 1,
  "numericCleanup": true,
  "saveCsv": true
}
```

### Output

Dataset: one item per table row, for example

```json
{"Region": "North", "Revenue Q1": 1200.5, "Revenue Q2": 1450, "_sourceUrl": "https://example.com/report", "_tableIndex": 0, "_rowIndex": 0}
```

Key-value store: `TABLES` (one entry per table: source, index, caption, rows, columns, file keys), `STATS` (counts and errors by code) and, if requested, the `table-*.csv` / `table-*.xlsx` files.

Error codes in `STATS.errors`: `http_404` and other statuses, `blocked_by_robots_txt`, `robots_txt_unavailable`, `timeout`, `dns_failure`, `page_too_large`, `unsupported_content_type`, `invalid_url`, `blocked_private_address`, `invalid_selector`, `no_tables_found`.

### Good to know

- Static HTML only. Tables that a page builds with JavaScript after loading are not in the HTML this Actor reads.
- You are responsible for the terms of use of the sites you extract from and for what you do with the data. This Actor fetches only the URLs you provide.
- `_tableIndex` counts the tables matched by your selector (all tables if none), in document order.

### More tools from the same developer

- [HTML to Markdown Converter for LLM and RAG](https://apify.com/ucchiii/html-to-markdown) — clean Markdown from URLs, raw HTML or datasets for LLM and RAG
- [CSV to Excel Converter](https://apify.com/ucchiii/csv-xlsx-converter) — convert CSV, TSV, Excel XLSX, JSON and NDJSON files or Apify datasets into each other
- [Website to Markdown Crawler for RAG and LLMs](https://apify.com/ucchiii/website-markdown-crawler) — crawl a website and get every page as clean Markdown for RAG and LLMs, robots.txt respected, optional chunks
- [JSON to CSV Converter](https://apify.com/ucchiii/json-to-csv) — turn nested JSON files or datasets into one flat CSV file

# Actor input Schema

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

Full page URLs starting with http:// or https:// that contain HTML tables. Only these pages are fetched (no crawling, no login); internal or private addresses are refused. Leave URLs and HTML empty for a free demo.

## `htmlStrings` (type: `array`):

Raw HTML documents to read tables from, one string per document (up to 5 MB each). Use this when you already have the HTML, for example from your own scraper.

## `baseUrl` (type: `string`):

Optional http(s) URL written to \_sourceUrl for the raw HTML strings. If empty, \_sourceUrl is html#0, html#1 and so on.

## `tableSelector` (type: `string`):

Optional CSS selector, e.g. table.wikitable or #prices. It can point at a table or at a container whose tables you want. Empty means every table on the page.

## `tableIndexes` (type: `array`):

Optional list of 0-based positions of the tables to keep, counted among the tables the selector matched, e.g. \[0, 2]. Empty means all matched tables.

## `minRows` (type: `integer`):

Skip tables with fewer data rows than this (the header is not counted). Use 2 or more to ignore layout tables and tiny widgets.

## `maxTablesPerPage` (type: `integer`):

Stop reading a page after this many tables. Each table is charged once, so this caps the cost per page.

## `headerMode` (type: `string`):

How column names are found. Auto uses thead or the leading rows made of th cells and merges multi-row headers; empty names become column_N and duplicates get a \_2 suffix.

## `fillSpans` (type: `boolean`):

Expand colspan and rowspan: the merged value is repeated in every cell it covers, so each row is complete. If off, only the first cell holds the value and the rest are empty.

## `numericCleanup` (type: `boolean`):

Turn values like $1,234.50, 12% or (5) into numbers (1234.5, 12, -5). Text, dates and codes with leading zeros stay as they are. Percent signs and currency symbols are dropped.

## `saveCsv` (type: `boolean`):

Also store one CSV file per table in the key-value store. File keys are listed in the TABLES record.

## `saveXlsx` (type: `boolean`):

Also store one .xlsx file per table in the key-value store. File keys are listed in the TABLES record.

## `respectRobotsTxt` (type: `boolean`):

Skip pages that the site's robots.txt disallows for bots (they are free). Keep this on unless you have the site owner's permission to ignore it.

## `maxRetries` (type: `integer`):

How often a page is retried after a timeout, connection error, 429 or 502/503/504, waiting 1, 2, 4 seconds and so on (or the server's Retry-After). Allowed range 0 to 5.

## `timeoutSecs` (type: `integer`):

Timeout for each page request, in seconds. Allowed range 1 to 120 (default 20).

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

How many pages are processed at once, across different sites. Each host gets one request at a time, at least 1 second apart. Allowed range 1 to 5.

## `userAgent` (type: `string`):

Optional custom User-Agent header. The default identifies this Actor as a generic bot that fetches only the URLs you provide.

## Actor input object example

```json
{
  "urls": [
    "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"
  ],
  "tableSelector": "table.wikitable",
  "minRows": 1,
  "maxTablesPerPage": 1,
  "headerMode": "auto",
  "fillSpans": true,
  "numericCleanup": false,
  "saveCsv": false,
  "saveXlsx": false,
  "respectRobotsTxt": true,
  "maxRetries": 3,
  "timeoutSecs": 20,
  "concurrency": 3
}
```

# Actor output Schema

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

One item per table row: the columns keyed by header, plus \_sourceUrl, \_tableIndex and \_rowIndex.

## `tables` (type: `string`):

Record TABLES: one entry per table with its columns, row count and, if requested, the CSV and Excel file keys.

## `stats` (type: `string`):

Record STATS: counts of tables, rows, charged tables and failed inputs by error code.

# 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 = {
    "urls": [
        "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"
    ],
    "tableSelector": "table.wikitable",
    "maxTablesPerPage": 1
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/html-table-extractor").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 = {
    "urls": ["https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"],
    "tableSelector": "table.wikitable",
    "maxTablesPerPage": 1,
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/html-table-extractor").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 '{
  "urls": [
    "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"
  ],
  "tableSelector": "table.wikitable",
  "maxTablesPerPage": 1
}' |
apify call ucchiii/html-table-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ucchiii/html-table-extractor"
        }
    }
}
```

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/zjDYOSBx0aB7TqhiD/builds/bpsIXLwar9ttf9S8y/openapi.json
