# Website & Sitemap to Markdown for RAG & LLM (`sequined_lacework/website-to-markdown-rag`) Actor

Convert web pages, documentation sites, and sitemaps into clean LLM-ready Markdown with preserved code blocks and RAG chunks. Fast, no browser.

- **URL**: https://apify.com/sequined_lacework/website-to-markdown-rag.md
- **Developed by:** [Egor Kramskoy](https://apify.com/sequined_lacework) (community)
- **Categories:** AI, Developer tools
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 pages scraped

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/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 & Sitemap to Markdown for RAG & LLM

**Website to Markdown** in one Apify Actor: send page URLs or a sitemap, get clean Markdown (headings, lists, tables, links) and optional ready-to-embed chunks. Use it as a fast **LLM web scraper**, to build **Sitemap to Markdown for RAG** datasets, or to **crawl documentation to Markdown**. It runs without a browser and charges per page.

### What it does

- Fetches web pages with plain HTTP (HTTP/2 when available) and extracts the main content with trafilatura. Menus, headers, footers, sidebars, cookie banners and ads are stripped.
- Accepts normal page URLs and **sitemaps**: `sitemap.xml`, sitemap index files (up to 5 levels) and gzipped `.xml.gz` sitemaps.
- Optionally follows internal links on the same host, only below the start URL's directory (for `https://docs.pydantic.dev/latest/` it stays inside `/latest/`).
- Keeps code blocks intact: fenced blocks with language, including MkDocs tabs, collapsible sections and blocks with line numbers or copy buttons.
- Splits the Markdown into overlapping chunks for vector databases when `chunkSize` is set.
- Returns title, description, language, word count and a token estimate for every page.

### Why use it

- **Clean output**: main content only, with Markdown tables and optional links.
- **No browser**: pure HTTP, so runs are fast and cheap.
- **Pay per page**: you pay only for pages that produced Markdown.
- **LLM-ready**: chunks plus token estimates help you plan context windows.
- **Failures do not stop the run**: a bad URL produces an item with `status: "error"` and a short `error_message` (for example `HTTP 404`).

### Input example

```json
{
    "startUrls": [
        "https://docs.pydantic.dev/latest/",
        "https://example.com/sitemap.xml"
    ],
    "maxPages": 50,
    "followInternalLinks": true,
    "includeTables": true,
    "includeLinks": true,
    "chunkSize": 1500,
    "chunkOverlap": 200,
    "maxConcurrency": 5
}
```

| Field | Default | Description |
|---|---|---|
| `startUrls` | demo docs page | Page URLs or sitemap URLs |
| `maxPages` | 50 | Max pages processed, successful and failed attempts both count (1-5000) |
| `followInternalLinks` | false | Crawl links found on pages, same host and below the start URL's directory |
| `includeTables` | true | Keep tables as Markdown tables |
| `includeLinks` | true | Keep hyperlinks as `[text](url)` |
| `chunkSize` | 0 | Chunk size in characters; 0 disables chunking (max 16000) |
| `chunkOverlap` | 200 | Overlap between chunks; reduced to `chunkSize / 4` if not smaller than `chunkSize` |
| `maxConcurrency` | 5 | Pages fetched in parallel (1-20) |

### Output example

One dataset item per page (markdown and chunks truncated here):

```json
{
    "source_url": "https://docs.pydantic.dev/latest/concepts/models/",
    "title": "Models",
    "description": "How to define and use Pydantic models.",
    "language": "en",
    "word_count": 4200,
    "estimated_tokens": 7100,
    "markdown": "# Models\n\nOne of the primary ways of defining schema in Pydantic is via models...\n\n| Method | Purpose |\n|---|---|\n| ... | ... |",
    "chunks": [
        "# Models\n\nOne of the primary ways of defining schema...",
        "...end of the previous chunk. Start of the next chunk..."
    ],
    "status": "ok",
    "error_message": null
}
```

The numbers above are illustrative. If a page is fetched but no main content can be extracted (for example a JavaScript-only page), the item has `status: "ok"`, empty `markdown` and `error_message: "no main content extracted"`.

### Pricing

Pay-per-event: **$0.02 per run start** (the `run-started` event, charged once per run that has at least one URL) plus **$0.001 per page** (the `page-scraped` event, one per page converted to non-empty Markdown). Example: one run with 1,000 pages costs $0.02 + 1,000 x $0.001 = **$1.02**. Failed requests and pages with no extracted content are not charged for pages; runs with no URLs are not charged at all.

The prices are not stored in the Actor code. `.actor/pay_per_event.json` documents the events and the suggested prices. The real prices and the Actor categories are set in Apify Console (Actor > Publication > Monetization / Categories).

### Use with Claude Desktop / Cursor (MCP)

Connect the Actor to any MCP client through the Apify MCP server: https://mcp.apify.com/?actors=sequined_lacework/website-to-markdown-rag

Add this to your Claude Desktop or Cursor MCP config (`mcpServers`):

```json
{
    "mcpServers": {
        "apify": {
            "url": "https://mcp.apify.com/?actors=sequined_lacework/website-to-markdown-rag",
            "headers": {
                "Authorization": "Bearer <YOUR_APIFY_TOKEN>"
            }
        }
    }
}
```

An AI agent can give the Actor a documentation site, blog post or sitemap URL and receive clean Markdown with code blocks and tables, so it can read live web pages instead of relying on stale training data.

### Integrations: n8n and LangChain

#### n8n

Use the **Apify** node (operation: Run Actor, then Get Dataset Items) with the Actor ID `sequined_lacework/website-to-markdown-rag`, or an **HTTP Request** node (method `POST`, body type JSON) pointing at the synchronous endpoint, which returns the dataset items directly:

```
https://api.apify.com/v2/acts/sequined_lacework~website-to-markdown-rag/run-sync-get-dataset-items?token=<YOUR_APIFY_TOKEN>
```

Body:

```json
{
    "startUrls": ["https://docs.pydantic.dev/latest/"],
    "maxPages": 20,
    "followInternalLinks": true,
    "chunkSize": 1500
}
```

Synchronous runs time out after 300 seconds, so use the regular run endpoint for large inputs.

#### LangChain (Python)

Install `langchain-apify` and `langchain-core`, and set the `APIFY_API_TOKEN` environment variable. The Markdown is in the `markdown` field and becomes the document `page_content`.

```python
from langchain_apify import ApifyWrapper
from langchain_core.documents import Document

apify = ApifyWrapper()
loader = apify.call_actor(
    actor_id="sequined_lacework/website-to-markdown-rag",
    run_input={"startUrls": ["https://docs.pydantic.dev/latest/"], "followInternalLinks": True, "maxPages": 20, "chunkSize": 1500},
    dataset_mapping_function=lambda item: Document(
        page_content=item["markdown"] or "",
        metadata={"source": item["source_url"], "title": item["title"]},
    ),
)
docs = [d for d in loader.load() if d.page_content]
```

To load an existing run instead, use `ApifyDatasetLoader(dataset_id="<DATASET_ID>", dataset_mapping_function=...)` from `langchain_apify` with the same mapping function. If you set `chunkSize`, the `chunks` field already holds ready-to-embed pieces, so no extra text splitter is needed.

### Free plan limits

On the free Apify plan the Actor runs in demo mode:

- At most **10 pages** per run in total (the lower of 10 and `maxPages`).
- The crawl stops after the limit; remaining pages are not fetched or charged.

The run never fails because of these limits, and the log and status message say when something was skipped. Upgrade to a paid Apify plan to process the full input.

### Related Actors for RAG Pipelines

Build a complete RAG ingestion pipeline with the same clean Markdown output, chunking options and pay-per-event pricing:

- [PDF to Markdown for RAG & LLM](https://apify.com/sequined_lacework/pdf-to-markdown-rag): PDFs (arXiv, Google Drive, any URL) with tables preserved
- [Website & Sitemap to Markdown for RAG & LLM](https://apify.com/sequined_lacework/website-to-markdown-rag) *(this Actor)*: docs sites, blogs and sitemaps, code blocks preserved
- [Podcast RSS & Transcript Extractor for AI/RAG](https://apify.com/sequined_lacework/podcast-transcript-rag): podcast episodes with publisher transcripts
- [GitHub Repository to Clean Markdown for LLM & RAG](https://apify.com/sequined_lacework/github-repo-to-markdown): whole codebases as one Markdown context with a file tree
- [RSS, Atom & Substack to Clean Markdown for RAG](https://apify.com/sequined_lacework/rss-article-markdown): blogs and newsletters, full articles from teaser feeds

### Limits

- **No JavaScript rendering.** Only the HTML returned by the server is processed. Single-page apps that build content in the browser may return empty or partial results.
- **robots.txt is not checked.** You are responsible for following the terms of service and crawling rules of the sites you scrape.
- Pages behind a login or paywall are not supported.
- Responses larger than 10 MB and non-text content types (PDF, images, archives) are skipped with an error.
- Links to files (`.pdf`, `.zip`, images, `.css`, `.js`, `.json`, `.xml` and similar) are not followed.
- Sitemaps are expanded up to 5 levels deep and up to `maxPages * 2` page links.

### FAQ

**Can I scrape a whole documentation site?**
Yes. Set the start URL to the docs root (for example `https://docs.pydantic.dev/latest/`), enable `followInternalLinks` and raise `maxPages`. Alternatively pass the site's `sitemap.xml`.

**Which engine is used?**
trafilatura for main-content extraction. If it finds nothing, a BeautifulSoup based fallback removes navigation and boilerplate and converts the rest to Markdown.

**How are tokens estimated?**
Roughly 4 characters per token, which is a rough figure for English text. Use your model's tokenizer for exact counts.

**Why is my output empty?**
The page is probably rendered with JavaScript, so the server HTML has no content. This Actor does not run a browser.

**How does `maxPages` count?**
Every attempted page counts, including failed ones, so a crawl always stops after at most `maxPages` requests for pages. Sitemap files themselves are not counted.

**Do I need to do anything to run it locally?**
`pip install -r requirements.txt`, then `apify run` (Apify CLI). Local runs skip charging automatically.

# Actor input Schema

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

Page URLs or sitemap URLs (sitemap.xml, sitemap index, .xml.gz). Sitemaps are expanded into their pages automatically.

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

Maximum number of pages to process (successful and failed attempts both count).

## `followInternalLinks` (type: `boolean`):

Also crawl links found on each page, but only on the same host and below the start URL's directory (e.g. /latest/...).

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

Keep tables as Markdown tables.

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

Keep hyperlinks as [text](url) in the Markdown.

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

If greater than 0, the Markdown is also split into RAG-ready chunks of at most this many characters. 0 disables chunking.

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

Approximate overlap between neighbouring chunks. Reduced automatically if not smaller than the chunk size.

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

How many pages are fetched in parallel.

## Actor input object example

```json
{
  "startUrls": [
    "https://docs.pydantic.dev/latest/"
  ],
  "maxPages": 1,
  "followInternalLinks": false,
  "includeTables": true,
  "includeLinks": true,
  "chunkSize": 0,
  "chunkOverlap": 200,
  "maxConcurrency": 5
}
```

# Actor output Schema

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

One item per crawled page with clean Markdown, metadata and optional RAG chunks.

# 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": [
        "https://docs.pydantic.dev/latest/"
    ],
    "maxPages": 1
};

// Run the Actor and wait for it to finish
const run = await client.actor("sequined_lacework/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": ["https://docs.pydantic.dev/latest/"],
    "maxPages": 1,
}

# Run the Actor and wait for it to finish
run = client.actor("sequined_lacework/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": [
    "https://docs.pydantic.dev/latest/"
  ],
  "maxPages": 1
}' |
apify call sequined_lacework/website-to-markdown-rag --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,sequined_lacework/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/1jhwZcOcLExh7xrmd/builds/Da2cJwFdcM7lBWghl/openapi.json
