# Wayback CDX → Markdown for RAG (`ingenious_quip_bxq/wayback-cdx-markdown`) Actor

Query the Wayback Machine CDX index, fetch selected snapshot HTML, and extract clean Markdown with trafilatura for RAG pipelines. Optional heading-aware chunks. Competitors often stop at CDX URL lists — this Actor returns page body Markdown.

- **URL**: https://apify.com/ingenious\_quip\_bxq/wayback-cdx-markdown.md
- **Developed by:** [新世紀書僮](https://apify.com/ingenious_quip_bxq) (community)
- **Categories:** AI, Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 snapshot markdowns

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

## Wayback CDX → Markdown for RAG

**Query the Wayback Machine CDX index, fetch selected snapshot HTML, and extract clean Markdown for RAG — not just a list of archive URLs.**

Many tools stop after listing CDX captures. This Actor uses open-source **waybackpack** (MIT) for CDX + snapshot fetch and **trafilatura** (Apache-2.0) to turn archived HTML into Markdown dataset rows, with optional heading-aware RAG chunks. Broken captures are reported, not fatal. Default memory: 256 MB. No browser, no AI keys.

### What you get

- 📚 **CDX search** — page URL(s) and/or domain prefix (`example.com/*`) via waybackpack
- 🗓️ **Filters** — date range, collapse (day/month/digest), status codes, MIME substrings
- 🎯 **Selection** — latest, oldest, or even sample; per-target and global caps
- 📝 **Markdown body** — trafilatura extraction (tables optional; comments off by default)
- 🧩 **Optional RAG chunks** — heading-aware chunks with token estimate
- 🧯 **Per-target report** — `CDX_REPORT` in the key-value store; failed fetches are free rows
- 💾 **HTTP only** — 256 MB default

### Measured results

Local + private cloud (2026-09-30 Asia/Taipei). Settled `usageTotalUsd` on own runs; see `docs/PRICING.md`.

| Test | Result |
|---|---|
| `example.com/` CDX 2024, collapse month, 2 snapshots + chunks (local) | **2** Markdown items + **2** chunks in **~47 s**; CDX 12→6→2 |
| `example.com/` + `info.cern.ch/` (2020, 1 snap each, local) | **2** Markdown items in **~40 s**; 0 fetch errors |
| Cloud 1 snapshot `bGbenU8jxfkK90zMh` (256 MB) | **1** item; ~66 s; memMax ~97 MB; settled **$0.001083** |
| Cloud 5 URLs × sample, max 10 `N3u4tjN3UeWN4J6hH` (build 0.1.2) | **10** items; ~202 s; memMax ~105 MB; settled **$0.003037** (~$0.00030 / snapshot) |
| Cloud 2 URLs + domain, items+chunks `tnMfOC9kJbluFSncc` | **7** items + **10** free chunks; ~96 s; memMax ~107 MB; settled **$0.001599** |

### Use cases

- **Rebuild historical page text** for RAG / knowledge bases from Wayback captures
- **Sample a site’s archived paths** under a domain and extract readable Markdown
- **Compare snapshots over time** (collapse by day/month, then extract)

### How to use

1. Add page **URLs** and/or **Domains**.
2. Optional: set **From/To date**, **Collapse**, **Max snapshots per URL/domain**, **Output**.
3. Start the Actor. Rows appear in the **Dataset**; `CDX_REPORT` and `OUTPUT` in the **Key-value store**.

#### Input example

```json
{
  "urls": [{ "url": "https://example.com/" }],
  "fromDate": "202401",
  "toDate": "202412",
  "maxSnapshotsPerTarget": 2,
  "maxItems": 5,
  "collapse": "timestamp:6",
  "selection": "latest",
  "outputFormat": "items",
  "delaySecs": 0.5
}
```

#### Output example (one dataset item per snapshot)

```json
{
  "kind": "snapshot",
  "status": "ok",
  "originalUrl": "https://example.com/",
  "archiveUrl": "https://web.archive.org/web/20241201001928id_/https://example.com/",
  "timestamp": "20241201001928",
  "title": "Example Domain",
  "contentMarkdown": "This domain is for use in documentation examples…",
  "contentHash": "sha256…",
  "wordCount": 26,
  "mimeType": "text/html",
  "statusCode": "200"
}
```

#### Key-value store records

| Key | Content |
|---|---|
| `CDX_REPORT` | Per-target CDX hits / selected / fetch ok-fail |
| `OUTPUT` | Run summary (counts, duration, charged events) |

### Pricing

**Pay per event** (private Actor; Store publish pending coordinator):

| Event | Price |
|---|---|
| `snapshot-item` (primary) | **$0.003** per successfully extracted snapshot Markdown |
| `apify-actor-start` | Apify default ($0.00005 / GB) |

Failed CDX queries and failed fetches are never charged. RAG chunk rows do not add extra events. Example: 1,000 snapshots ≈ **$3.00** list (+ actor-start). Details: `docs/PRICING.md`.

### Known limits

- Wayback CDX and snapshot endpoints rate-limit; use **Delay between snapshot fetches** and modest caps.
- Domain prefix queries (`example.com/*`) can return very large CDX sets — keep **Max snapshots per URL/domain** low and prefer date bounds.
- Some captures are redirects, soft-404s, or binary; trafilatura may return empty text (reported as error, not charged).
- waybackpack uses synchronous `requests` under the hood (run in a worker thread); not a headless browser.

### FAQ

**Does this publish captures to a public GitHub repo?** No. This project stays private unless you deliberately publish later.

**Do you copy closed Apify Actors?** No. Stack is waybackpack (MIT) + trafilatura (Apache-2.0) + the in-house Apify Python template patterns.

### License & source

Actor source: **AGPL-3.0** (see `LICENSE`). Third-party notices: `NOTICE`.

# Changelog

This Actor's version history is a separate document: https://apify.com/ingenious\_quip\_bxq/wayback-cdx-markdown/changelog.md

# Actor input Schema

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

Exact page URLs to look up in the Wayback CDX index (e.g. https://example.com/about). Paste a list or upload a text file.

## `domains` (type: `array`):

Optional. Bare domains or hostnames (e.g. example.com). Queried as `example.com/*` so CDX returns archived paths under that host. Use Max snapshots carefully — large sites have huge CDX result sets.

## `fromDate` (type: `string`):

Earliest snapshot timestamp prefix (YYYY, YYYYMM, YYYYMMDD, or full YYYYMMDDhhmmss). Passed to the CDX `from` parameter.

## `toDate` (type: `string`):

Latest snapshot timestamp prefix (same formats as From date). Passed to the CDX `to` parameter.

## `collapse` (type: `string`):

CDX `collapse` to reduce near-duplicates. `timestamp:8` ≈ one per day, `timestamp:6` ≈ one per month, `digest` = unique content digests, `none` = no collapse (can be huge).

## `uniquesOnly` (type: `boolean`):

When the CDX API returns dupecount, keep only rows with dupecount=0 (waybackpack `--uniques-only`).

## `statusCodes` (type: `array`):

Keep only CDX rows whose statuscode is in this list. Empty = keep all codes.

## `mimeTypes` (type: `array`):

Keep CDX rows whose mimetype contains any of these substrings (case-insensitive). Empty = no MIME filter. Default keeps HTML-ish captures.

## `selection` (type: `string`):

After filters, which snapshots to fetch: `latest` (newest first), `oldest` (oldest first), or `sample` (evenly spaced across the filtered list).

## `maxSnapshotsPerTarget` (type: `integer`):

Cap how many snapshots are fetched for each input URL or domain after filters/selection.

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

Stop after this many successfully extracted snapshot rows (0 = no limit). Also caps cost.

## `fetchRaw` (type: `boolean`):

Use Wayback `id_` flag so the Machine returns the original capture without toolbar rewriting (waybackpack `--raw`). Recommended for extraction.

## `outputFormat` (type: `string`):

`items`: one dataset row per extracted snapshot. `chunks`: RAG chunk rows + a short per-snapshot summary row. `items_and_chunks`: both full items and chunk rows.

## `includeComments` (type: `boolean`):

Pass include\_comments to trafilatura (default off — usually noise on archived pages).

## `includeTables` (type: `boolean`):

Pass include\_tables to trafilatura.

## `favorPrecision` (type: `boolean`):

trafilatura favor\_precision=True — less noise, possibly less text.

## `chunkSize` (type: `integer`):

Maximum chunk size (unit below). Used when Output includes chunks.

## `chunkOverlap` (type: `integer`):

Trailing context repeated at the start of the next chunk.

## `chunkUnit` (type: `string`):

`tokens` ≈ 4 characters per token; `characters` is exact.

## `requestTimeoutSecs` (type: `integer`):

Timeout for CDX and snapshot HTTP requests.

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

Retries for Wayback CDX / snapshot fetches (waybackpack Session max\_retries).

## `delaySecs` (type: `number`):

Polite pause between snapshot body downloads. CDX queries are not delayed.

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

Optional. Wayback asks tools to identify themselves (include a contact). Default mentions waybackpack + this Actor.

## Actor input object example

```json
{
  "urls": [
    {
      "url": "https://example.com/"
    }
  ],
  "collapse": "timestamp:8",
  "uniquesOnly": false,
  "statusCodes": [
    "200"
  ],
  "mimeTypes": [
    "text/html",
    "html"
  ],
  "selection": "latest",
  "maxSnapshotsPerTarget": 2,
  "maxItems": 5,
  "fetchRaw": true,
  "outputFormat": "items",
  "includeComments": false,
  "includeTables": true,
  "favorPrecision": false,
  "chunkSize": 1000,
  "chunkOverlap": 150,
  "chunkUnit": "tokens",
  "requestTimeoutSecs": 60,
  "maxRetries": 3,
  "delaySecs": 0.5
}
```

# Actor output Schema

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

Default dataset items. Snapshot rows include: kind, status, originalUrl, archiveUrl, timestamp, title, contentMarkdown, contentHash, wordCount, mimeType, statusCode, digest. Chunk rows include chunkIndex, text, headingPath, tokenEstimate. Views: overview, chunks.

## `cdxReport` (type: `string`):

Key-value store record CDX\_REPORT (JSON array): one entry per input URL/domain with cdxHits, selected, fetchedOk, fetchedFailed, error.

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

Key-value store record OUTPUT (JSON): targets, itemsOutput, chunksOutput, cdxHits, fetchErrors, durationSecs.

# 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": [
        {
            "url": "https://example.com/"
        }
    ],
    "statusCodes": [
        "200"
    ],
    "mimeTypes": [
        "text/html",
        "html"
    ],
    "maxSnapshotsPerTarget": 2,
    "maxItems": 5
};

// Run the Actor and wait for it to finish
const run = await client.actor("ingenious_quip_bxq/wayback-cdx-markdown").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": [{ "url": "https://example.com/" }],
    "statusCodes": ["200"],
    "mimeTypes": [
        "text/html",
        "html",
    ],
    "maxSnapshotsPerTarget": 2,
    "maxItems": 5,
}

# Run the Actor and wait for it to finish
run = client.actor("ingenious_quip_bxq/wayback-cdx-markdown").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": [
    {
      "url": "https://example.com/"
    }
  ],
  "statusCodes": [
    "200"
  ],
  "mimeTypes": [
    "text/html",
    "html"
  ],
  "maxSnapshotsPerTarget": 2,
  "maxItems": 5
}' |
apify call ingenious_quip_bxq/wayback-cdx-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ingenious_quip_bxq/wayback-cdx-markdown"
        }
    }
}
```

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/JbLFtMbaPuxLFtwl3/builds/VabxHpDc7MD4jGrVt/openapi.json
