# Website to Markdown for AI: RAG-ready chunks (`opstoolkit/website-to-markdown-rag`) Actor

Give it a website URL, get clean markdown per page plus token counts and overlapping chunks for RAG and vector databases. Reads the sitemap, respects robots.txt. $1.50 per 1,000 pages. Re-runs charge only for new or changed pages.

- **URL**: https://apify.com/opstoolkit/website-to-markdown-rag.md
- **Developed by:** [Elio Saliba](https://apify.com/opstoolkit) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.50 / 1,000 page converteds

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

## Website to Markdown for AI: RAG-ready chunks

Give it a website URL and get clean markdown for every page, with menus, footers and cookie banners removed, plus a token estimate and overlapping chunks sized for your embedding model. Each chunk carries the section path it sits under.

Built for people feeding documentation, help centres and blogs into a vector database, a chatbot or a fine-tuning set.

**$1.50 per 1,000 pages converted.** Chunking is included. Re-runs can charge only for pages that are new or changed. Apify's free monthly credit covers a first test at no cost.

### What you get

One dataset row per page (or one row per chunk, your choice), plus a `SUMMARY` record with counts and everything that was skipped.

| Field | Example | What it is for |
|---|---|---|
| `markdown` | `# EOQ formula: how to calculate ...` | The page body: headings, lists, code blocks, tables, links |
| `chunks` | 4 chunks of about 450 tokens | Ready for embeddings, with `headingPath` for each one |
| `title`, `description`, `lang`, `canonical` | `EOQ Formula and Worked Example` | Metadata for filtering and citations |
| `publishedAt`, `modifiedAt`, `author` | `2026-11-18` | Read from the page's meta tags and JSON-LD when present |
| `wordCount`, `tokenEstimate` | `1251`, `1760` | Plan your embedding budget before you embed |
| `contentHash` | `8e6658c6...` | Detect changes between runs |
| `changeType` | `new` or `changed` | Only set when you use re-run mode |

### How to use

1. **Enter a website**, for example `https://docs.example.com`. The Actor reads the sitemap from `robots.txt` or `/sitemap.xml`. With no sitemap it follows links from the start page.
2. **Set Max pages.** Start with 10 to see the output, then raise it.
3. **Narrow it down** with "Only these URLs", for example `/docs/*`, if you want one section of a site.
4. **Press Start.** Open the dataset, or call the API from your pipeline.

For a vector database, set **Dataset rows** to "One row per chunk". Each row is flat: `chunkId`, `url`, `title`, `headingPath`, `text`.

### Use it from an AI agent

In Claude, ChatGPT or Cursor, add the Apify MCP server (https://mcp.apify.com) and ask in plain words. The agent finds this Actor (`opstoolkit/website-to-markdown-rag`), fills in the input from your sentence, runs it and reads the result back.

Example prompt: "Read the docs at https://docs.example.com, up to 200 pages, and give me one row per chunk so I can load them into my vector database."

The agent gets flat rows with `chunkId`, `url`, `title`, `headingPath` and `text`, or one row per page with `markdown` and `tokenEstimate`. A `SUMMARY` record lists skipped pages and any PDF links found.

### Input example

```json
{
  "startUrls": [{ "url": "https://opstoolkit-816.netlify.app/guides/" }],
  "maxPages": 10,
  "includeUrlPatterns": ["/guides/*"],
  "chunkSize": 512,
  "chunkOverlap": 64,
  "outputMode": "pages"
}
```

- **Chunk size** is in estimated tokens (about 4 characters each, one per CJK character). Paragraphs, lists, code blocks and tables stay whole when they fit. A heading never ends a chunk.
- **Chunk overlap** repeats the end of the previous chunk, so a sentence keeps its context.
- **Only new or changed pages** keeps a fingerprint of each page between runs. The next run skips pages that did not change. Skipped pages are not returned and not charged.
- **Keep images** and **Keep links** control what the markdown contains. Images are off by default.
- **Main content selector** and **Remove these elements** are for the odd site where automatic detection picks the wrong block.

### Output example

From a real run on a public site (shortened):

```json
{
  "url": "https://opstoolkit-816.netlify.app/guides/eoq-formula-example",
  "title": "EOQ Formula and Worked Example | OpsToolkit",
  "lang": "en",
  "publishedAt": "2026-11-18",
  "changeType": "new",
  "wordCount": 1251,
  "tokenEstimate": 1760,
  "headings": ["EOQ formula: how to calculate economic order quantity, with a worked example", "The EOQ formula", "Worked example: a coffee supplier"],
  "markdown": "# EOQ formula: how to calculate economic order quantity, with a worked example\n\nEconomic order quantity (EOQ) tells you how many units to buy per order ...",
  "chunkCount": 4,
  "chunks": [
    {
      "chunkId": "52bb759a10-1",
      "index": 1,
      "tokenEstimate": 444,
      "headingPath": ["EOQ formula: how to calculate economic order quantity, with a worked example", "Worked example: a coffee supplier", "Step 3: the yearly costs"],
      "text": "Orders per year = D / EOQ = 4,800 / 464.76 = 10.33 ...\n\n### Step 3: the yearly costs\n\n| Cost per year | Formula | Amount |\n| --- | --- | --- |\n| Ordering | D / Q × S | $464.76 |"
    }
  ]
}
```

A 40-page run on a small site produced 155 chunks (about 61,000 tokens) in 17 seconds, on 512 MB. The `SUMMARY` record from a 5-page run:

```json
{
  "pagesConverted": 5,
  "pagesFetched": 5,
  "chunks": 19,
  "tokensEstimated": 7713,
  "unchangedPagesSkipped": 0,
  "skippedByReason": {},
  "failedPages": 0,
  "failed": [],
  "documentLinks": []
}
```

`skippedByReason` counts pages that were left out (`too_short`, `duplicate`, `robots_txt`, `not_html`, `left_site`), and `skipped` lists each URL. `documentLinks` lists the PDF and Word files the site links to. Feed them to the companion Actor, [Document to Markdown for AI](https://apify.com/opstoolkit/document-to-markdown-rag).

### What it removes

Navigation, headers and footers, sidebars, breadcrumbs, cookie and consent banners, newsletter pop-ups, share buttons, "related posts" blocks, hidden elements, scripts and styles. It finds the main content from `<main>`, `<article>` or common content containers, and falls back to a readability score when a page has none.

### Use cases

- **Support bots**: load a help centre and refresh it every week, paying only for pages that changed.
- **Documentation search**: one chunk per section, each with its heading path for citations.
- **Fine-tuning and evaluation sets**: clean text with source URL and date on every row.
- **Competitor and market research**: read a site's public pages into your own notes tool.

### Pricing

Pay per event: **$1.50 per 1,000 pages converted** ($0.0015 per page). Chunking, token counts and metadata are included. Apify adds a small fee for each run start.

| Site size | Cost |
|---|---|
| 100 pages | $0.15 |
| 1,000 pages | $1.50 |
| 10,000 pages | $15 |

- Pages that fail, are blocked by robots.txt, are too short, are duplicates or (in re-run mode) did not change are free.
- Set **Max pages**, or a maximum cost per run in Apify, to cap what a run can spend.

**Compared with other options.** Website Content Crawler by Apify charges for platform usage, which Apify's own page puts at about $0.20 per 1,000 pages for plain HTTP and $0.50 to $5 for a browser, so the cost depends on the site. Other pay-per-result crawlers on the Store charge about $3 per 1,000 pages. On plain HTML sites its usage cost can be lower than $1.50. What this Actor adds is a flat price you can budget, chunks with heading paths already made, and a re-run mode that bills only for changes. It reads plain HTML only. For sites that need a browser to show their content, use Website Content Crawler.

### How it treats other people's servers

- It follows robots.txt, including `Crawl-delay` (up to 10 seconds). Disallowed pages are skipped.
- It sends at most one request every 250 ms to a site, with 5 pages in flight. Both are settings.
- It stays on the site you gave it. Links to other domains are not followed.
- It refuses addresses on private networks, so it cannot be pointed at internal services.

### Limits

- It reads the HTML the server sends. Content added later by JavaScript (many single-page apps) is not seen. Pages with almost no text are skipped and listed.
- Pages behind a login are not supported.
- Token counts are estimates, usually within 10 to 15 percent of OpenAI tokenizers on English text. Use them to size chunks and budgets, not to bill.
- Up to 50,000 pages and 20 start URLs per run. Pages over 5 MB are cut at 5 MB.
- PDF and Word files linked from a page are listed in `SUMMARY`, not converted here.

### Using the output

**LangChain, from the chunk rows:**

```python
from apify_client import ApifyClient
from langchain_core.documents import Document

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("opstoolkit/website-to-markdown-rag").call(run_input={
    "startUrls": [{"url": "https://docs.example.com"}],
    "outputMode": "chunks",
    "maxPages": 200,
})
docs = [
    Document(page_content=row["text"],
             metadata={"source": row["url"], "title": row["title"], "section": " > ".join(row["headingPath"])})
    for row in client.dataset(run["defaultDatasetId"]).iterate_items()
]
```

**LlamaIndex:**

```python
from llama_index.core import Document, VectorStoreIndex

nodes = [Document(text=row["text"], metadata={"url": row["url"], "title": row["title"]})
         for row in client.dataset(run["defaultDatasetId"]).iterate_items()]
index = VectorStoreIndex.from_documents(nodes)
```

**Keeping a vector database fresh.** Schedule the Actor weekly with "Only new or changed pages" on. Each run returns only new and changed pages. Delete the old vectors for a returned `url` before you insert the new ones. `SUMMARY.sites[].removedSinceLastRun` lists pages that now return 404 or disappeared from a complete crawl.

Everything Apify supports works here: schedules, webhooks, the REST API, and the integrations with Zapier, Make, n8n, Pinecone, Qdrant and others. The **API** tab has ready code for JavaScript, Python and cURL.

### Works well with

- **[Document to Markdown for AI](https://apify.com/opstoolkit/document-to-markdown-rag)**: `SUMMARY.documentLinks` lists the PDF and Word files the site links to. Pass those links to it in `documentUrls` to get the same markdown and chunks for the files.
- **[Image and Scanned PDF OCR](https://apify.com/opstoolkit/image-pdf-ocr)**: if one of those PDFs is a scan with no text layer, Document to Markdown reports it as failed and does not charge. Send the link to OCR instead.
- **[AI Structured Extractor](https://apify.com/opstoolkit/ai-structured-extractor)**: when you want fields (price, plan name, date) instead of prose, give it this run's dataset with `datasetId` and `field` set to `markdown` (use **One row per page**).
- **[Sitemap URL Extractor](https://apify.com/opstoolkit/sitemap-url-extractor)**: list a site's URLs first to see its sections, then write **Only these URLs** patterns and a sensible **Max pages**.

A typical chain: this Actor for pages, AI Structured Extractor for records, then [Dataset Cleaner](https://apify.com/opstoolkit/dataset-cleaner) to remove duplicates and normalize prices, dates and phones.

### FAQ

**Can I crawl any website?**
Any public site that allows it in robots.txt. Check the site's terms for how you may use the content.

**Why was a page skipped?**
Open `SUMMARY`. Each skipped page has a reason: `robots_txt`, `too_short`, `duplicate`, `not_html` or `left_site`. Failed pages list the HTTP status or the error.

**The text of my page is missing.**
The page probably builds its content with JavaScript. Check the source with "view page source". If the text is not there, this Actor cannot see it.

**Can it follow only some sections?**
Yes. Use "Only these URLs" (`/docs/*`) and "Skip these URLs" (`/docs/archive/*`). Patterns that start with `/` match the path. Other patterns match the whole URL, with `*` as a wildcard.

**Something broke.**
Open an issue on the Issues tab with the run link. I reply within a day.

# Changelog

This Actor's version history is a separate document: https://apify.com/opstoolkit/website-to-markdown-rag/changelog.md

# Actor input Schema

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

Start pages of the websites to convert, up to 20. Example: https://docs.example.com. Only pages on the same site as a start URL are read. Pages come from the site's sitemap, found through robots.txt or /sitemap.xml, or by following links when there is none.

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

Total number of pages to convert in this run, from 1 to 50,000. Default 100. You pay per page converted, so use a small number such as 10 for a first test.

## `includeUrlPatterns` (type: `array`):

Keep only URLs that match one of these patterns. \* is a wildcard. A pattern that starts with / is matched against the path, so /docs/\* keeps pages under /docs/. Any other pattern is matched against the full URL. Default empty, which reads the whole site.

## `excludeUrlPatterns` (type: `array`):

Skip URLs that match one of these patterns. Same rules as 'Only these URLs'. Skip wins when a URL matches both. Examples: /blog/tag/\*, */changelog*. Default empty.

## `discovery` (type: `string`):

How pages are found. 'sitemap-then-crawl' (default) reads the sitemap and follows links only when there is none. 'sitemap' reads only the pages the sitemap lists. 'crawl' ignores the sitemap and follows links from the start page.

## `sitemapUrl` (type: `string`):

Full address of the sitemap, for example https://docs.example.com/sitemap.xml. Only needed when it is not listed in robots.txt or at /sitemap.xml, and used when you give one start URL. Leave empty otherwise.

## `maxCrawlDepth` (type: `integer`):

How many link clicks away from the start page to follow, from 0 to 30. Default 5. 0 reads only the start page. Used only when links are followed; ignored when a sitemap is used.

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

Target size of each chunk in estimated tokens (about 4 characters each), from 0 to 8,000. Default 512, which suits most embedding models. 0 skips chunking and returns markdown only.

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

Tokens repeated from the end of the previous chunk, so a sentence keeps its context. Default 64, from 0 to 4,000. It must not be more than half of the chunk size, or the run stops with an input error.

## `prependHeadingsToChunks` (type: `boolean`):

When on, each chunk's text starts with its heading path (page title > section > subsection). This helps retrieval when a chunk is read alone. Default off, so the text stays exactly as on the page.

## `outputMode` (type: `string`):

What one dataset row is. 'pages' (default): one row per page with its markdown and chunks inside. 'chunks': one flat row per chunk (chunkId, url, title, headingPath, text), ready for a vector database. The price is per page either way.

## `onlyNewOrChanged` (type: `boolean`):

When on, the Actor remembers a fingerprint of every page between runs and returns only pages that are new or changed. Unchanged pages are not returned and not charged. Use it for scheduled refreshes of a vector database. Default off.

## `stateStoreName` (type: `string`):

Name of the memory of past runs, used only with 'Only new or changed pages'. Runs with the same name share the memory. Letters, numbers and dashes only. Default 'website-markdown-state'.

## `includeLinks` (type: `boolean`):

When on (default), hyperlinks stay as markdown links. Turn it off for plain text without URLs.

## `includeImages` (type: `boolean`):

When on, images stay as markdown image tags. Default off, because most embedding pipelines ignore images.

## `minWords` (type: `integer`):

Pages with fewer words than this are skipped and not charged. They are listed in the SUMMARY record. Default 10, from 0 to 100,000.

## `contentSelector` (type: `string`):

CSS selector that forces which part of the page is the main content. Example: article.post or #docs-body. Leave empty (default) to detect the content area automatically.

## `removeSelectors` (type: `array`):

CSS selectors of elements to delete before conversion. Example: \[".promo-banner", "#survey"]. Default empty.

## `maxConcurrency` (type: `integer`):

How many pages are fetched at the same time, from 1 to 20. Default 5. Keep it low for small sites.

## `requestDelayMs` (type: `integer`):

Minimum pause between requests to one website, in milliseconds, from 0 to 10,000. Default 250. A Crawl-delay in robots.txt is used instead when it is longer.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://opstoolkit-816.netlify.app/guides/"
    }
  ],
  "maxPages": 10,
  "includeUrlPatterns": [
    "/guides/*"
  ],
  "discovery": "sitemap-then-crawl",
  "maxCrawlDepth": 5,
  "chunkSize": 512,
  "chunkOverlap": 64,
  "prependHeadingsToChunks": false,
  "outputMode": "pages",
  "onlyNewOrChanged": false,
  "stateStoreName": "website-markdown-state",
  "includeLinks": true,
  "includeImages": false,
  "minWords": 10,
  "maxConcurrency": 5,
  "requestDelayMs": 250
}
```

# Actor output Schema

## `pages` (type: `string`):

No description

## `summary` (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 = {
    "startUrls": [
        {
            "url": "https://opstoolkit-816.netlify.app/guides/"
        }
    ],
    "maxPages": 10,
    "includeUrlPatterns": [
        "/guides/*"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("opstoolkit/website-to-markdown-rag").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://opstoolkit-816.netlify.app/guides/" }],
    "maxPages": 10,
    "includeUrlPatterns": ["/guides/*"],
}

# Run the Actor and wait for it to finish
run = client.actor("opstoolkit/website-to-markdown-rag").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://opstoolkit-816.netlify.app/guides/"
    }
  ],
  "maxPages": 10,
  "includeUrlPatterns": [
    "/guides/*"
  ]
}' |
apify call opstoolkit/website-to-markdown-rag --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,opstoolkit/website-to-markdown-rag"
        }
    }
}
```

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/xsumuzlReYIj3Yes2/builds/2HgJUlw2BQSjha1KV/openapi.json
