Skip to main content
TutorialsDecember 1, 2026 · 32 min read

How to crawl a documentation website for RAG

Turn a public documentation site into RAG-ready Markdown: map the pages, fetch them, clean the text, chunk it safely and test retrieval.

How to crawl a documentation website for RAG

To crawl a documentation website for RAG, you need more than its pages. A docs site comes with a navigation menu on every page, translated and old-version copies of the same article, headings full of anchor links, and code blocks that a careless splitter will cut in half. Feed all of that to a retrieval-augmented assistant, and it answers from the wrong version, quotes menus, or hands back Python with no indentation.

This tutorial builds a dataset you can trust: one clean source URL and title for every page, and chunk-ready Markdown that keeps its code intact. It records why each page was kept or skipped, and ends with a retrieval test.

Install the packages and put your Spidra key in the environment as SPIDRA_API_KEY:

# pip install spidra httpx rank-bm25 snowballstemmer
import argparse
import hashlib
import json
import os
import re
import sys
import time

from collections import Counter
from dataclasses import dataclass
from datetime import datetime, timezone
from fnmatch import fnmatch
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qsl, urlencode, urlsplit

import httpx
from rank_bm25 import BM25Okapi
from snowballstemmer import stemmer
from spidra import (
    CrawlParams,
    Spidra,
    SpidraAuthenticationError,
    SpidraError,
    SpidraJobFailedError,
    SpidraPaymentRequiredError,
    SpidraRateLimitError,
    SpidraServerError,
    SpidraTimeoutError,
    SpidraValidationError,
)

The plan

Seven steps turn a site into a dataset, and each one answers a failure you'd otherwise find later:

  1. Map the site to see every page it exposes.
  2. Select the pages worth ingesting, and record why each other page was skipped.
  3. Fetch the Markdown, with failures reported instead of hidden.
  4. Clean it: navigation, anchors and site names out.
  5. Chunk it by heading, without cutting a code block.
  6. Store the chunks with their source URL, title and heading path.
  7. Test retrieval before you trust it.

See the site first with Map

Map lists a site's URLs without scraping them, from its sitemap and its links. A search term ranks the best matches first. Here it is on the Python docs, using a real response:

# needs SPIDRA_API_KEY
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
site = client.map("https://docs.python.org/3/", search="asyncio", limit=20)
print(site.total, "matched,", site.scanned, "scanned")
for link in site.links[:3]:
    print(link.url, "|", link.title)

Output:

21 matched, 556 scanned
https://docs.python.org/3/library/asyncio.html | asyncio
https://docs.python.org/3/library/asyncio-threading.html | asyncio and free-threaded Python
https://docs.python.org/3/howto/a-conceptual-overview-of-asyncio.html | A conceptual overview of asyncio

This call asked for pages about asyncio. Map read 556 URLs and returned the 21 that matched, best first. Each title is the text of the link that led to the page, and a URL found only in the sitemap has no title at all, so the pipeline below falls back to the page's own heading.

Map shows what a site exposes, and what it exposes isn't always what you want. Here is a real run on the FastAPI docs:

# needs SPIDRA_API_KEY
site = client.map("https://fastapi.tiangolo.com/", search="dependencies", limit=10)
print(site.total, "URLs matched,", site.scanned, "scanned")
for link in site.links[:5]:
    print(link.url)

Output:

36 URLs matched, 619 scanned
https://fastapi.tiangolo.com/tutorial/dependencies/
https://fastapi.tiangolo.com/reference/dependencies/
https://fastapi.tiangolo.com/de/reference/dependencies/
https://fastapi.tiangolo.com/es/reference/dependencies/
https://fastapi.tiangolo.com/fr/reference/dependencies/

Three of the five URLs are German, Spanish and French copies of one reference page. A RAG dataset built from this list would answer in the wrong language, and would count the same page four times. Choosing pages is a step of its own.

A docs site to practice on

To run everything offline, this tiny made-up docs site and stand-in client return what Map and batch scrape return. Raw pages carry the navigation and footer that a crawl keeps, and extract_content_only removes them:

BASE = "https://docs.example.test"
FENCE = "`" * 3
TOP = "[Skip to content](#main)\n\n* [Docs](/docs/)\n* [Sign in](/login)\n\n"
END = "\nWas this page helpful?\n\n© 2026 Example, Inc. All rights reserved.\n"
AUTH = "# Authentication [¶](#authentication)\n\nEvery request needs an API key. Send it in "
AUTH += "the `Authorization` header as a bearer token. Without a valid key, a request fails.\n"
AUTH += "\n## Rotating keys [¶](#rotating)\n\nCreate a new key, deploy it, then revoke the old "
AUTH += "one. Both keys work during the overlap, so a rotation never needs downtime.\n"
RATE = "# Rate limits [¶](#rate)\n\nEach key can send 60 requests a minute. Over that, the API "
RATE += "answers with the status code 429 and a `Retry-After` header that says how long to wait.\n"
LOOP = "def iter_notes(client):\n    cursor = None\n    while True:\n"
LOOP += "        page = client.list(cursor)\n        yield from page.items\n"
LOOP += "        cursor = page.next_cursor\n        if not cursor:\n            return"
INTRO = "# Pagination [¶](#pagination)\n\nPass `next_cursor` back until it is empty.\n\n"
PAGES = {"/docs/authentication": AUTH, "/docs/rate-limits": RATE}
PAGES["/docs/pagination"] = f"{INTRO}{FENCE}python\n{LOOP}\n{FENCE}\n"
PAGES["/docs/de/authentication"] = "# Authentifizierung\n\nSenden Sie Ihren Schlüssel im Header.\n"
PAGES["/docs/v1/pagination"] = "# Pagination (v1)\n\nVersion 1 used page numbers.\n"
TOPICS = {
    "errors": ("Errors", "A 401 means the API key is missing or invalid, and a 404 means "
               "the note does not exist. Retry 429 and 5xx with exponential backoff."),
    "webhooks": ("Webhooks", "The API calls your server when a note is created. Each call is "
                 "signed, so verify the signature header against your signing secret."),
    "sdk-python": ("Python SDK", "Install the client with pip. It needs Python 3.9 or newer, "
                   "and every method takes a timeout in seconds. A timeout raises an "
                   "error that you can catch and retry."),
    "getting-started": ("Getting started", "Create an account, copy your API key and install "
                        "the client. Then create your first note and read it back by its id. "
                        "Notes are private to your account."),
}
for slug, (title, text) in TOPICS.items():
    PAGES[f"/docs/{slug}"] = f"# {title} [¶](#{slug})\n\n{text}\n"
class TinyDocs:
    def map(self, url, search=None, limit=500, respect_robots=False):
        paths = [*PAGES, "/docs/assets/diagram.png", "/pricing"]
        links = [SimpleNamespace(url=BASE + p, title=None) for p in paths]
        return SimpleNamespace(links=links, total=len(links), scanned=len(links) + 30)

    def batch_scrape(self, urls, output="markdown", extract_content_only=False):
        page = lambda u: PAGES[u[len(BASE) :]]
        text = lambda u: page(u) if extract_content_only else TOP + page(u) + END
        make = lambda u: SimpleNamespace(url=u, status="completed", result=text(u), error=None)
        return SimpleNamespace(items=[make(u) for u in urls])

Choose pages, and keep the reasons

A page should be in the dataset because a rule said so, and a page left out should have a recorded reason. The rules here drop other sections, files, translated and versioned copies, and duplicates. The reasons are the same kind a crawl reports:

LOCALES = set("de es fr it ja ko pt ru zh nl pl tr ar hi id vi uk cs sv zh-cn zh-tw pt-br".split())
VERSION = re.compile(r"^v?\d+(\.\d+)*$", re.I)
FILE_TYPES = tuple("." + e for e in "png jpg jpeg gif svg webp pdf zip gz mp4 css js".split())
TRACKING = re.compile(r"^(utm_.+|gclid|fbclid)$", re.I)


def page_key(url):
    """One key per page: host, path without a trailing slash, query without tracking."""
    parts = urlsplit(url.strip())
    query = urlencode(sorted(q for q in parse_qsl(parts.query) if not TRACKING.match(q[0])))
    return f"{(parts.hostname or '').lower()}{parts.path.rstrip('/')}" + (
        f"?{query}" if query else ""
    )
def segments(path):
    """The lowercase parts of a URL path, without the empty ones."""
    return [s.lower() for s in path.split("/") if s]
def skip_reason(url, section, exclude=()):
    """Why a URL is left out, or an empty string to keep it. The first rule that matches wins."""
    path = urlsplit(url).path
    base, found = segments(section), segments(path)
    extra = found[len(base) :] if found[: len(base)] == base else []
    if found[: len(base)] != base:
        return "outside_section"
    if path.lower().endswith(FILE_TYPES):
        return "file_type"
    if any(s in LOCALES for s in extra):
        return "translated"
    if any(VERSION.match(s) for s in extra):
        return "other_version"
    return "excluded" if any(fnmatch(path, pattern) for pattern in exclude) else ""
def select_pages(links, section, exclude=()):
    """Split mapped links into pages to fetch and pages skipped, each skip with its reason."""
    kept, skipped, seen = [], [], set()
    for link in links:
        reason = skip_reason(link.url, section, exclude) or (
            "duplicate" if page_key(link.url) in seen else ""
        )
        seen.add(page_key(link.url))
        (skipped if reason else kept).append(
            {"url": link.url, "title": link.title, **({"reason": reason} if reason else {})}
        )
    return kept, skipped
def count_reasons(skipped):
    """How many pages were skipped for each reason, the most common reason first."""
    return dict(Counter(row["reason"] for row in skipped).most_common())

skip_reason returns the first rule a URL breaks, and select_pages splits the mapped links into pages to fetch and pages skipped, each with its reason. A trailing slash or a tracking parameter doesn't make a second page.

client = TinyDocs()
site = client.map(BASE + "/docs/")
keep, skipped = select_pages(site.links, "/docs/")
print("keep:", [k["url"].replace(BASE, "") for k in keep])
for row in skipped:
    print("skip:", row["url"].replace(BASE, ""), "->", row["reason"])

Output:

keep: ['/docs/authentication', '/docs/rate-limits', '/docs/pagination', '/docs/errors', '/docs/webhooks', '/docs/sdk-python', '/docs/getting-started']
skip: /docs/de/authentication -> translated
skip: /docs/v1/pagination -> other_version
skip: /docs/assets/diagram.png -> file_type
skip: /pricing -> outside_section

Seven pages are kept. The German copy, the version 1 page, the image and the pricing page are each skipped with a reason, so a missing page can always be explained.

Fetch the Markdown

You have two ways to fetch what you chose. If you already have the URLs, batch scrape them, which is simpler and more predictable. Batch scrape applies extract_content_only to every page, which strips the navigation, header, footer and sidebars. A batch reports completed even when some items failed, so each item needs its own check:

@dataclass
class Page:
    url: str
    title: str
    markdown: str
    source: str  # "batch" or "crawl"
    status: str = "ok"  # "ok" or "failed"
    error: str = ""
def page_from_item(item, titles):
    ok = item.status == "completed" and bool(item.result)
    error = "" if ok else str(item.error or item.status)
    return Page(
        item.url,
        titles.get(item.url) or "",
        item.result if ok else "",
        "batch",
        "ok" if ok else "failed",
        error,
    )
def batch_pages(client, urls, titles):
    """One batch of up to 50 URLs. It says completed even if items failed, so check each."""
    batch = client.batch_scrape(urls, output="markdown", extract_content_only=True)
    return [page_from_item(item, titles) for item in batch.items]
def fetch_batch(client, urls, titles=None, size=50, retries=1):
    """Fetch in groups of 50, then give the failed ones another go."""
    titles, done, todo = titles or {}, {}, list(urls)
    for _ in range(retries + 1):
        for start in range(0, len(todo), size):
            for page in batch_pages(client, todo[start : start + size], titles):
                done[page.url] = page
        todo = [u for u in urls if done.get(u) is None or done[u].status == "failed"]
        if not todo:
            break
    return [done[u] for u in urls if u in done]

fetch_batch sends up to 50 URLs at a time and retries the failed ones once. A page that still fails comes back marked as failed, with its error, so it appears in the manifest.

pages = fetch_batch(client, [k["url"] for k in keep])
for p in pages:
    print(p.status, p.url.replace(BASE, ""), len(p.markdown), "characters")

Output:

ok /docs/authentication 325 characters
ok /docs/rate-limits 173 characters
ok /docs/pagination 288 characters
ok /docs/errors 155 characters
ok /docs/webhooks 158 characters
ok /docs/sdk-python 191 characters
ok /docs/getting-started 193 characters

Or crawl

If you can't list the pages, Crawl follows links toward pages you describe. On a docs site, set crawl_entire_domain with include_paths, because sibling pages aren't under the start URL. Always ask it to respect robots.txt, since the default is not to. This is a real run on the Python docs:

# needs SPIDRA_API_KEY
job = client.crawl(CrawlParams(
    base_url="https://docs.python.org/3/library/asyncio.html",
    crawl_instruction="Individual Python asyncio reference pages",
    crawl_entire_domain=True, include_paths=["/3/library/asyncio*"], max_pages=5,
))
for page in job.result:
    markdown = httpx.get(page.markdown, timeout=30).text
    print(page.url.rsplit("/", 1)[-1], len(markdown), "characters", markdown.count("```") // 2, "code blocks")

Output:

asyncio-runner.html 10407 characters 2 code blocks
asyncio-task.html 59841 characters 32 code blocks
asyncio-stream.html 22038 characters 11 code blocks
asyncio-subprocess.html 17414 characters 4 code blocks
asyncio-queue.html 11371 characters 1 code blocks

The crawl returned five pages, and the contents page it started from was read for links and not returned. A crawl's Markdown is the whole page, navigation included, and the link to each page's Markdown is signed and expires, so read it at once and keep the page's own URL as the citation. These functions do that, and read the crawl's report:

def download(link):
    """Crawl results hold a signed link that expires, so read it right away."""
    response = httpx.get(link, timeout=30)
    response.raise_for_status()
    return response.text
def wait_for_crawl(client, job_id, poll=3.0, timeout=600.0, sleep=time.sleep):
    waited = 0.0
    while waited <= timeout:
        state = client.get_crawl(job_id)
        if state.status == "completed":
            return state
        if state.status in ("failed", "cancelled"):
            raise RuntimeError(
                f"the crawl {state.status}: {getattr(state, 'error', '') or ''}".strip()
            )
        sleep(poll)
        waited += poll
    raise TimeoutError("the crawl did not finish in time")
def crawl_pages(state, read):
    """The pages a crawl returned, with each Markdown link read straight away."""
    pages = []
    for item in state.result:
        try:
            pages.append(Page(item.url, item.title or "", read(item.markdown), "crawl"))
        except (httpx.HTTPError, OSError) as error:
            pages.append(Page(item.url, item.title or "", "", "crawl", "failed", str(error)))
    return pages
def start_params(start_url, include_paths, max_pages):
    return CrawlParams(
        base_url=start_url,
        crawl_instruction="Individual documentation pages",
        crawl_entire_domain=True,
        include_paths=include_paths,
        max_pages=max_pages,
        respect_robots=True,
    )
def fetch_crawl(
    client, start_url, include_paths, max_pages=50, read=download, poll=3.0, sleep=time.sleep
):
    """Crawl instead of map and batch. Returns the pages and the crawl's own report."""
    job_id = client.start_crawl(start_params(start_url, include_paths, max_pages)).job_id
    state = wait_for_crawl(client, job_id, poll, sleep=sleep)
    return crawl_pages(state, read), crawl_report(client, job_id)
def crawl_report(client, job_id):
    """What the crawl understood, how many pages it only read, and what it skipped."""
    report = client.crawl_report(job_id).report
    skipped = {row.reason: row.count for row in report.skipped}
    return {
        "understood_as": report.understood_as,
        "navigation_pages": report.navigation_pages,
        "skipped_total": report.skipped_total,
        "skipped": skipped,
    }

The report is what to read when a page you expected is missing. It gives what the crawl understood you to want, how many pages it only read to find others (free), and the skipped pages by reason, such as not_relevant, outside_start_path or file_type.

Know where the code is

Cleaning and chunking both need one fact about every line: is it inside a fenced code block? A # there is a Python comment, not a heading, and a menu-like line there is code, not chrome. One small reader answers it for everything that follows:

OPENING = re.compile(r"^ {0,3}(`{3,}|~{3,})([^`]*)$")


def closes(line, marker):
    """A closing fence is only fence characters, at least as many as the opening one."""
    text = line.strip()
    return len(text) >= len(marker) and text == text[0] * len(text) and text[0] == marker[0]
def walk(markdown):
    """Yield (line, in_code) for every line. The fence lines themselves count as code."""
    marker = ""
    for line in markdown.splitlines():
        opening = None if marker else OPENING.match(line)
        if marker:
            yield line, True
            marker = "" if closes(line, marker) else marker
        elif opening:
            marker = opening.group(1)
            yield line, True
        else:
            yield line, False
text = f"before\n{FENCE}python\n# not a heading\n  x = 1\n{FENCE}\nafter"
for line, in_code in walk(text):
    print(in_code, repr(line))

Output:

False 'before'
True '```python'
True '# not a heading'
True '  x = 1'
True '```'
False 'after'

walk yields each line with a flag, and counts the fence lines themselves as code. The indented line comes through exactly as written, and the comment is marked as code, so nothing downstream will mistake it for a heading.

Clean the Markdown

A crawl's Markdown includes the site's navigation and footer. Batch scrape with content-only drops them, but not heading anchors such as ### [Coroutines](#id2), which appeared in a real chunk's heading path. Cleaning handles both, and it has to leave code alone:

HEADING = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$")
PERMALINK = re.compile(r"\s*\[(?:¶|#|[Pp]ermalink[^\]]*)?\]\(#[^)]*\)")
ANCHOR_LABEL = re.compile(r"\[([^\]]+)\]\(#[^)]*\)")
LINK_ONLY = re.compile(r"^\s*(?:[*+-]|\d+\.)?\s*(?:\[[^\]]*\]\([^)]*\)[\s|,·•-]*)+$")
PAGER = re.compile(r"^\s*\[?\s*(?:←|→|«|»)?\s*(?:Previous|Next)\b", re.I)
SEPARATORS = (" | ", " - ", " – ", " — ")


def clean_heading(line):
    """'### [Coroutines](#id2)' becomes '### Coroutines', and a trailing [¶](#x) disappears."""
    found = HEADING.match(line)
    if not found:
        return line
    text = ANCHOR_LABEL.sub(r"\1", PERMALINK.sub("", found.group(2)))
    return f"{found.group(1)} {text.strip()}"
def strip_anchors(markdown):
    """Clean every heading outside a code block, and leave the code alone."""
    lines = [line if in_code else clean_heading(line) for line, in_code in walk(markdown)]
    return "\n".join(lines)
def is_candidate(line):
    """Lines that can be page chrome: link-only lines or very short plain lines, never headings."""
    text = line.strip()
    return (
        bool(text) and not text.startswith("#") and (bool(LINK_ONLY.match(line)) or len(text) <= 60)
    )


def lines_outside_code(markdown):
    return [line.strip() for line, in_code in walk(markdown) if not in_code and is_candidate(line)]
def find_boilerplate(pages, min_share=0.6, min_pages=3):
    """Lines that repeat on most pages are the site's chrome, so they aren't documentation."""
    if len(pages) < min_pages:
        return set()
    counts = Counter(line for page in pages for line in set(lines_outside_code(page)))
    return {line for line, seen in counts.items() if seen / len(pages) >= min_share}


def is_pager(line):
    """'[Previous: Pagination](/docs/pagination)' is chrome too, though it differs on every page."""
    return bool(PAGER.match(line) and LINK_ONLY.match(line))
def drop_lines(markdown, boilerplate):
    kept = [
        line
        for line, in_code in walk(markdown)
        if in_code or not (line.strip() in boilerplate or is_pager(line))
    ]
    return "\n".join(kept)
def tidy(markdown):
    """Trim trailing spaces and collapse runs of blank lines, but never inside a code block."""
    out, blank = [], 0
    for line, in_code in walk(markdown):
        blank = 0 if (in_code or line.strip()) else blank + 1
        if in_code or blank <= 1:
            out.append(line if in_code else line.rstrip())
    return "\n".join(out).strip("\n") + "\n"


def clean_markdown(markdown, boilerplate=frozenset()):
    return tidy(drop_lines(strip_anchors(markdown), boilerplate))
def content_chars(markdown):
    """Characters of real content: prose and code, but not headings or link lists."""
    return sum(len(line.strip()) for line, in_code in walk(markdown) if in_code or is_prose(line))


def is_prose(line):
    return bool(line.strip()) and not line.lstrip().startswith("#") and not LINK_ONLY.match(line)
def common_suffix(titles, min_share=0.6):
    """The site name that most titles end with, such as ' | Quillbase Docs'. Empty if none."""
    ends = [s + t.rpartition(s)[2] for t in titles for s in SEPARATORS if s in t]
    if len(titles) < 2 or not ends:
        return ""
    suffix, seen = Counter(ends).most_common(1)[0]
    return suffix if seen / len(titles) >= min_share else ""


def clean_title(title, suffix):
    """The title without the site name. A missing title (None) becomes an empty one."""
    title = (title or "").strip()
    return title[: -len(suffix)].strip() if suffix and title.endswith(suffix) else title
def first_heading(markdown):
    """The first level-1 heading outside a code block, for pages that arrive without a title."""
    for line, in_code in walk(markdown):
        found = None if in_code else HEADING.match(line)
        if found and len(found.group(1)) == 1:
            return found.group(2).strip()
    return ""

strip_anchors cleans headings but never code. find_boilerplate finds lines that repeat on most pages, which is how a menu gives itself away, and never counts a heading or a code line. is_pager removes Previous and Next links, which differ on every page. content_chars counts prose and code, so a page of mostly code isn't mistaken for an empty one.

paths = ["/docs/authentication", "/docs/pagination", "/docs/rate-limits"]
raw = [client.batch_scrape([BASE + p]).items[0].result for p in paths]
boiler = find_boilerplate(raw)
print(raw[0].strip(), "\n\n--- cleaned ---\n")
print(clean_markdown(raw[0], boiler))

Output:

[Skip to content](#main)

* [Docs](/docs/)
* [Sign in](/login)

# Authentication [¶](#authentication)

Every request needs an API key. Send it in the `Authorization` header as a bearer token. Without a valid key, a request fails.

## Rotating keys [¶](#rotating)

Create a new key, deploy it, then revoke the old one. Both keys work during the overlap, so a rotation never needs downtime.

Was this page helpful?

© 2026 Example, Inc. All rights reserved. 

--- cleaned ---

# Authentication

Every request needs an API key. Send it in the `Authorization` header as a bearer token. Without a valid key, a request fails.

## Rotating keys

Create a new key, deploy it, then revoke the old one. Both keys work during the overlap, so a rotation never needs downtime.

Menu lines, the footer and the heading anchors are gone, and the text is untouched. Lines that appear on most pages were found by comparing pages, so cleaning only works on a set of pages, not on one.

Chunk without breaking code

Chunking is where docs ingestion fails quietly. In langchain-text-splitters 1.2.0, MarkdownHeaderTextSplitter correctly ignores a # comment inside a code block, but it strips the leading whitespace from every line, so Python code loses its indentation. RecursiveCharacterTextSplitter keeps indentation, but it can cut a code block in half, leaving one chunk with an opening fence and no close and the next with a close and no opening. Chaining the two does both.

The chunker below splits by heading, treats a code block as one unit, and cuts an oversized one only between lines, closing and reopening the fence. It never touches indentation:

SENTENCE = re.compile(r"(?<=[.!?])\s+")


def sections(markdown, max_level=4):
    """(heading path, lines) for each section. A heading only counts outside a code block."""
    stack, lines, out = [], [], []
    for line, in_code in walk(markdown):
        found = None if in_code else HEADING.match(line)
        if found and len(found.group(1)) <= max_level:
            out.append(([text for _, text in stack], lines))
            level = len(found.group(1))
            stack = [(lv, t) for lv, t in stack if lv < level] + [(level, found.group(2))]
            lines = []
        lines.append(line)
    return out + [([text for _, text in stack], lines)]
def blocks(lines):
    """Paragraphs and whole code blocks. A code block is never broken up here."""
    out, buf, in_block = [], [], False
    for line, in_code in walk("\n".join(lines)):
        if in_code != in_block or (not in_code and not line.strip()):
            out += ["\n".join(buf)] if any(x.strip() for x in buf) else []
            buf, in_block = [], in_code
        if in_code or line.strip():
            buf.append(line)
    return out + (["\n".join(buf)] if any(x.strip() for x in buf) else [])
def split_code(block, limit):
    """Cut an oversized code block between lines, and close and reopen its fence each time."""
    rows = block.split("\n")
    opener = rows[0]
    marker = OPENING.match(opener).group(1)
    body = rows[1:-1] if closes(rows[-1], marker) and len(rows) > 1 else rows[1:]
    room = max(limit - len(opener) - len(marker) - 2, 1)
    parts, cur = [], []
    for row in body:
        if cur and sum(len(r) + 1 for r in cur) + len(row) > room:
            parts.append(cur)
            cur = []
        cur.append(row)
    parts.append(cur)
    return ["\n".join([opener, *part, marker]) for part in parts]
def split_text(text, limit):
    """Cut a long paragraph at sentence ends, and at spaces only when a sentence is too long."""
    pieces, cur = [], ""
    for sentence in SENTENCE.split(text):
        for word_run in (
            [sentence]
            if len(sentence) <= limit
            else re.findall(r".{1,%d}(?:\s+|$)" % limit, sentence)
        ):
            if cur and len(cur) + 1 + len(word_run) > limit:
                pieces.append(cur)
                cur = ""
            cur = f"{cur} {word_run}".strip()
    return pieces + [cur]
def fit(block, limit):
    if len(block) <= limit:
        return [block]
    return (
        split_code(block, limit)
        if OPENING.match(block.split("\n")[0])
        else split_text(block, limit)
    )
def pack(parts, limit):
    """Fill each chunk with whole blocks until the next one would not fit."""
    chunks, cur = [], ""
    for block in (piece for part in parts for piece in fit(part, limit)):
        if cur and len(cur) + 2 + len(block) > limit:
            chunks.append(cur)
            cur = ""
        cur = f"{cur}\n\n{block}" if cur else block
    return chunks + ([cur] if cur else [])


def chunk_id(url, path, text):
    return hashlib.sha1(f"{url}|{' > '.join(path)}|{text}".encode("utf-8")).hexdigest()[:12]
def has_body(parts):
    return any(not HEADING.match(p) for p in parts)


def make_chunk(url, title, path, text, index):
    return {
        "id": chunk_id(url, path, text),
        "url": url,
        "title": title,
        "heading_path": path,
        "index": index,
        "text": text,
    }
def chunk_page(url, title, markdown, max_chars=1200):
    """One dict per chunk, with the source URL, title and heading path that produced it."""
    out = []
    for path, lines in sections(markdown):
        parts = blocks(lines)
        for text in pack(parts, max_chars) if has_body(parts) else []:
            out.append(make_chunk(url, title, path, text, len(out)))
    return out


def embed_text(chunk):
    """What to embed or index: the breadcrumb tells a chunk which page and section it came from."""
    return " > ".join([chunk["title"], *chunk["heading_path"]]) + "\n\n" + chunk["text"]

sections follows the heading path, and a heading inside a code block never starts a section. pack fills each chunk with whole blocks. Each chunk keeps its page URL, title and heading path, and its id comes from them and its text, so the same text always gets the same id.

text = clean_markdown(PAGES["/docs/pagination"])
for c in chunk_page(BASE + "/docs/pagination", "Pagination", text, max_chars=160):
    print(c["heading_path"], len(c["text"]), "chars,", c["text"].count(FENCE), "fence marks")
print(c["text"])

Output:

['Pagination'] 56 chars, 0 fence marks
['Pagination'] 136 chars, 2 fence marks
['Pagination'] 89 chars, 2 fence marks
```python
        cursor = page.next_cursor
        if not cursor:
            return
```

At a deliberately small limit, the code block was cut between lines into parts that each have an opening and a closing fence. The last chunk shows the indentation intact.

Store the dataset with its provenance

The pipeline joins the steps. Every mapped URL ends up as one row of a manifest, whether it was included, skipped or failed, so the dataset can be audited:

def utc_now():
    return datetime.now(timezone.utc)

def page_hash(markdown):
    return hashlib.sha1(markdown.encode("utf-8")).hexdigest()[:16]


def map_site(client, url, search=None, limit=500):
    """Every URL Map can see. robots.txt is respected, because the default is not to."""
    return client.map(url, search=search, limit=limit, respect_robots=True)


def slug_title(url):
    return url.rstrip("/").rsplit("/", 1)[-1].replace("-", " ").replace("_", " ").capitalize()
def title_for(page, clean, suffix):
    """The title without the site name. Map gives none for sitemap-only URLs, so fall back."""
    return clean_title(page.title, suffix) or first_heading(clean) or slug_title(page.url)


def clean_pages(pages):
    """Clean every page. Lines that repeat across the whole set are found first."""
    ok = [p for p in pages if p.status == "ok"]
    boiler = find_boilerplate([p.markdown for p in ok])
    suffix = common_suffix([p.title for p in ok if p.title])
    cleaned = [(p, clean_markdown(p.markdown, boiler)) for p in ok]
    return [(p, clean, title_for(p, clean, suffix)) for p, clean in cleaned]
def skipped_row(url, reason, title=""):
    """A manifest row for a page that was left out, and why."""
    return {"url": url, "title": title, "status": "skipped", "reason": reason}
def included_row(page, clean, title, count, now):
    sizes = {"raw_chars": len(page.markdown), "clean_chars": len(clean), "chunks": count}
    return {
        "url": page.url,
        "title": title,
        "status": "included",
        "reason": "",
        "source": page.source,
        **sizes,
        "page_hash": page_hash(clean),
        "fetched_at": now.isoformat(),
    }
def failed_row(page):
    return {
        "url": page.url,
        "title": page.title,
        "status": "failed",
        "reason": "fetch_failed",
        "error": page.error,
    }
def one_page(page, clean, title, max_chars, min_content, now):
    """A page's manifest row and its chunks. A page with too little real content is skipped."""
    pieces = (
        chunk_page(page.url, title, clean, max_chars) if content_chars(clean) >= min_content else []
    )
    return (
        included_row(page, clean, title, len(pieces), now)
        if pieces
        else skipped_row(page.url, "too_little_text", title)
    ), pieces
def page_rows(pages, max_chars, min_content, now):
    rows, chunks = [], []
    for page, clean, title in clean_pages(pages):
        row, pieces = one_page(page, clean, title, max_chars, min_content, now)
        rows.append(row)
        chunks += pieces
    return rows, chunks


def build_dataset(pages, skipped=(), max_chars=1200, min_content=120, clock=utc_now):
    """Turn fetched pages into manifest rows and chunks. Nothing is dropped without a reason."""
    rows = [skipped_row(s["url"], s["reason"], s.get("title", "")) for s in skipped]
    rows += [failed_row(p) for p in pages if p.status == "failed"]
    more, chunks = page_rows(pages, max_chars, min_content, clock())
    return {"pages": rows + more, "chunks": chunks}
def summarize(dataset):
    rows = dataset["pages"]
    left_out = [r for r in rows if r["status"] != "included"]
    return {
        "included": len(rows) - len(left_out),
        "chunks": len(dataset["chunks"]),
        "failed": sum(r["status"] == "failed" for r in rows),
        "skipped": count_reasons([r for r in left_out if r["status"] == "skipped"]),
    }
def ingest_batch(
    client, url, section, search=None, limit=500, exclude=(), max_chars=1200, clock=utc_now
):
    """Map, choose, batch scrape, clean, chunk. The mapped URLs and the skips come back too."""
    site = map_site(client, url, search, limit)
    keep, skipped = select_pages(site.links, section, exclude)
    pages = fetch_batch(client, [k["url"] for k in keep], {k["url"]: k["title"] for k in keep})
    return {
        **build_dataset(pages, skipped, max_chars, clock=clock),
        "mapped": len(site.links),
        "scanned": site.scanned,
    }
def ingest_crawl(
    client, start_url, include_paths, max_pages=50, max_chars=1200, read=None, clock=utc_now
):
    """Crawl instead. The crawl's own report says what it skipped."""
    kwargs = {"read": read} if read else {}
    pages, report = fetch_crawl(client, start_url, include_paths, max_pages, **kwargs)
    return {**build_dataset(pages, (), max_chars, clock=clock), "crawl_report": report}
def write_jsonl(path, rows):
    with open(path, "w", encoding="utf-8") as handle:
        handle.writelines(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)


def read_jsonl(path):
    lines = Path(path).read_text(encoding="utf-8").splitlines()
    return [json.loads(line) for line in lines if line.strip()]


def save_dataset(dataset, folder):
    """pages.jsonl has a row for every page, included or not. chunks.jsonl has the text."""
    Path(folder).mkdir(parents=True, exist_ok=True)
    write_jsonl(Path(folder) / "pages.jsonl", dataset["pages"])
    write_jsonl(Path(folder) / "chunks.jsonl", dataset["chunks"])
def diff_manifests(old, new):
    """Compare two runs by page hash: what is new, gone, changed, or the same."""
    before = {r["url"]: r["page_hash"] for r in old if r.get("page_hash")}
    after = {r["url"]: r["page_hash"] for r in new if r.get("page_hash")}
    return {
        "added": sorted(set(after) - set(before)),
        "removed": sorted(set(before) - set(after)),
        "changed": sorted(u for u in after if u in before and after[u] != before[u]),
        "unchanged": sorted(u for u in after if u in before and after[u] == before[u]),
    }

build_dataset skips a page with too little content, such as a contents page, and records that too. Each included page gets a hash of its cleaned text, which makes the next run's comparison cheap. The stores are plain files: pages.jsonl has a row for every page, and chunks.jsonl has the text to index.

dataset = ingest_batch(client, BASE + "/docs/", "/docs/")
print(summarize(dataset))
chunk = dataset["chunks"][1]
print(json.dumps({k: chunk[k] for k in ("id", "url", "title", "heading_path")}, indent=2))

Output:

{'included': 7, 'chunks': 8, 'failed': 0, 'skipped': {'translated': 1, 'other_version': 1, 'file_type': 1, 'outside_section': 1}}
{
  "id": "f022ee44be0e",
  "url": "https://docs.example.test/docs/authentication",
  "title": "Authentication",
  "heading_path": [
    "Authentication",
    "Rotating keys"
  ]
}

Every chunk can be traced to a clean URL, a title and a heading path, and no heading carries an anchor.

Test retrieval before you trust it

A dataset isn't ready until questions find their pages. This test uses BM25, which needs no API key, with stemming so that "authenticate" finds "authentication". Swap in embeddings later and keep the same test questions:

STEM = stemmer("english").stemWord
STOP = set("a an and are as at be by can do does for from how i in is it".split()) | set(
    "of on or that the to what when with you your".split()
)


def tokens(text):
    """Lowercase, stemmed words. A snake_case name is kept whole and also split into its parts."""
    words = re.findall(r"[a-z0-9_]+", text.lower())
    parts = [w for word in words for w in ([word, *word.split("_")] if "_" in word else [word])]
    return [STEM(w) for w in parts if w and w not in STOP]
class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.bm25 = BM25Okapi([tokens(embed_text(c)) for c in chunks])

    def search(self, query, k=3):
        scores = self.bm25.get_scores(tokens(query))
        order = sorted(range(len(scores)), key=lambda i: (-scores[i], i))[:k]
        return [
            {"score": round(float(scores[i]), 2), **self.chunks[i]} for i in order if scores[i] > 0
        ]
def hit_rate(index, tests, k=3):
    """The share of test questions whose expected page shows up in the top k chunks."""
    misses = [(q, want) for q, want in tests if want not in {r["url"] for r in index.search(q, k)}]
    return {
        "asked": len(tests),
        "hit": len(tests) - len(misses),
        "rate": (len(tests) - len(misses)) / len(tests) if tests else 0.0,
        "misses": misses,
    }

hit_rate asks each test question and checks whether the expected page appears in the top results. Raw and cleaned text can be compared on the same questions:

urls = [p.url for p in pages]
raw = [Page(u, "", client.batch_scrape([u]).items[0].result, "batch") for u in urls]
raw_index = Index([c for p in raw for c in chunk_page(p.url, p.title, p.markdown)])
clean_index = Index(dataset["chunks"])
questions = {
    "How do I authenticate requests?": "/docs/authentication",
    "What is the rate limit?": "/docs/rate-limits",
    "How do I get the next page of results?": "/docs/pagination",
    "How do I verify a webhook?": "/docs/webhooks",
    "How do I install the Python SDK?": "/docs/sdk-python",
}
tests = [(question, BASE + path) for question, path in questions.items()]
for name, index in (("raw", raw_index), ("cleaned", clean_index)):
    found = hit_rate(index, tests, k=1)
    print(name, f"{found['hit']} of {found['asked']} questions found their page first")

Output:

raw 4 of 5 questions found their page first
cleaned 5 of 5 questions found their page first

Cleaned text found all five pages first, and raw text missed one: for "How do I get the next page of results?" it ranked Getting started above Pagination. That is one question on a made-up site, so read it as a mechanism and not as a benchmark. Menu and footer text repeats on every page, which dilutes the words that make a page distinctive. The other difference is what the model reads once a page is found:

def chrome(index):
    hits = [h for q, _ in tests for h in index.search(q, 3)]
    return sum("Skip to content" in h["text"] or "helpful" in h["text"] for h in hits)


print("results carrying site chrome:", chrome(raw_index), "raw,", chrome(clean_index), "cleaned")
print("first raw chunk:    ", repr(raw_index.chunks[0]["text"][:34]))
print("first cleaned chunk:", repr(clean_index.chunks[0]["text"][:34]))

Output:

results carrying site chrome: 10 raw, 0 cleaned
first raw chunk:     '[Skip to content](#main)\n\n* [Docs]'
first cleaned chunk: '# Authentication\n\nEvery request ne'

Ten of the raw results carried menu or footer text, and none of the cleaned results did. The first raw chunk is pure navigation, and the first cleaned chunk is the start of the page. That's text a model reads and tokens you pay for.

A caution about the test itself: BM25 weighs a word by how rare it is, so over a handful of chunks a word that appears in half of them scores zero, and a good question can return nothing at all. Test with enough pages for the scores to mean something, and keep the same questions when you swap in embeddings.

Keep it fresh

Documentation changes, so ingestion recurs. Map again, fetch again, and compare page hashes with the last manifest: re-embed only what changed, and drop the chunks of pages that disappeared.

before = dataset["pages"]
PAGES["/docs/rate-limits"] += "\n## Headers\n\nEvery response carries `X-RateLimit-Remaining`.\n"
after = ingest_batch(client, BASE + "/docs/", "/docs/")["pages"]
print({key: len(urls) for key, urls in diff_manifests(before, after).items()})

Output:

{'added': 0, 'removed': 0, 'changed': 1, 'unchanged': 6}

One page changed, and six stayed the same. That's the whole refresh: no new pages appeared, and none vanished, so only one page's chunks need to be re-indexed.

The finished command

The command runs all of it, writes pages.jsonl and chunks.jsonl, and can print a test search, score your test questions and report what changed since the last run. Failures need a message and an exit code, so a scheduler can tell them apart:

NO_API_KEY = 3  # missing or rejected
RULES = [
    (
        SpidraAuthenticationError,
        NO_API_KEY,
        "the Spidra API key was rejected. Check SPIDRA_API_KEY.",
    ),
    (SpidraPaymentRequiredError, 4, "the account is out of credits, or its payment is overdue."),
    (SpidraRateLimitError, 5, "too many requests. Wait a moment and try again."),
    (SpidraTimeoutError, 6, "Spidra took too long to answer."),
    (SpidraJobFailedError, 7, None),  # its own message says what failed
    (SpidraValidationError, 8, None),  # its own message says which option was refused
    (SpidraServerError, 9, "Spidra had a problem on its side. Try again."),
]
UNKNOWN = 1
NO_PAGES = 10  # nothing on the site matched
BAD_OPTIONS = 11  # the options can't be used together
SOME_FAILED = 12  # the dataset was written, but some pages could not be fetched


class Failure(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.message, self.code = message, code
def explain(error):
    """The first rule that matches wins. List the specific errors before the general one."""
    for kind, code, text in RULES:
        if isinstance(error, kind):
            return Failure(text or str(error), code)
    return Failure(str(error), UNKNOWN)


def failure_from(error):
    return explain(error) if isinstance(error, SpidraError) else Failure(str(error), UNKNOWN)
def split_list(text):
    return [part.strip() for part in (text or "").split(",") if part.strip()]


def add_site_options(ask):
    ask.add_argument("url", help="a page on the docs site, such as its docs index")
    ask.add_argument("--section", help="keep only pages under this path (default: the URL's path)")
    ask.add_argument("--search", help="only URLs related to these words")
    ask.add_argument("--limit", type=int, default=500, help="URLs to map, 1 to 5000")
    ask.add_argument("--exclude", help="comma-separated path patterns to leave out")
    ask.add_argument("--crawl", action="store_true", help="crawl instead of map and batch scrape")
    ask.add_argument("--max-pages", type=int, default=50, help="pages a crawl may return")
def build_parser():
    ask = argparse.ArgumentParser(description="Turn a documentation site into a RAG-ready dataset.")
    add_site_options(ask)
    ask.add_argument("--max-chars", type=int, default=1200, help="largest chunk, in characters")
    ask.add_argument("--out", default="data", help="folder for pages.jsonl and chunks.jsonl")
    ask.add_argument("--query", help="run a test search over the new chunks")
    ask.add_argument("--tests", help="a JSON file of [{question, url}] to score retrieval")
    ask.add_argument("--previous", help="an earlier pages.jsonl, to report what changed")
    return ask


def make_client():
    if not os.environ.get("SPIDRA_API_KEY"):
        raise Failure("set SPIDRA_API_KEY to your Spidra key first.", NO_API_KEY)
    return Spidra(api_key=os.environ["SPIDRA_API_KEY"], api_url=os.environ.get("SPIDRA_API_URL"))
def ingest(args, client, read):
    section = args.section or urlsplit(args.url).path or "/"
    if args.crawl:
        return ingest_crawl(
            client, args.url, [section.rstrip("/") + "*"], args.max_pages, args.max_chars, read
        )
    return ingest_batch(
        client, args.url, section, args.search, args.limit, split_list(args.exclude), args.max_chars
    )
def summary_lines(dataset):
    s = summarize(dataset)
    skipped = ", ".join(f"{reason} {count}" for reason, count in s["skipped"].items()) or "none"
    return [
        f"Included {s['included']} pages as {s['chunks']} chunks",
        f"Skipped: {skipped}",
        f"Failed: {s['failed']}",
    ]


def show_search(index, query):
    lines = [f'Test search: "{query}"']
    for hit in index.search(query, 3):
        lines.append(f"  {hit['score']:>5}  {hit['url']}  [{' > '.join(hit['heading_path'])}]")
    return lines
def diff_line(args, dataset):
    diff = diff_manifests(read_jsonl(args.previous), dataset["pages"])
    return [
        "Changed since last run: " + ", ".join(f"{key} {len(urls)}" for key, urls in diff.items())
    ]


def score_line(index, path):
    tests = [(t["question"], t["url"]) for t in json.loads(Path(path).read_text(encoding="utf-8"))]
    found = hit_rate(index, tests)
    return [
        f"Retrieval: {found['hit']} of {found['asked']} questions found their page in the top 3"
    ]
def extras(args, dataset):
    """The optional steps: what changed since last time, a test search, and a retrieval score."""
    index = Index(dataset["chunks"]) if dataset["chunks"] and (args.query or args.tests) else None
    lines = diff_line(args, dataset) if args.previous else []
    lines += show_search(index, args.query) if index and args.query else []
    return lines + (score_line(index, args.tests) if index and args.tests else [])


def run(args, client, read):
    dataset = ingest(args, client, read)
    save_dataset(dataset, args.out)
    print("\n".join(summary_lines(dataset) + extras(args, dataset)))
    if not summarize(dataset)["included"]:
        raise Failure("no pages were ingested. Check the URL and --section.", NO_PAGES)
    return SOME_FAILED if summarize(dataset)["failed"] else 0
def main(argv=None, client=None, read=None):
    args = build_parser().parse_args(argv)
    try:
        if args.limit < 1 or args.max_chars < 100:
            raise Failure("--limit must be at least 1 and --max-chars at least 100.", BAD_OPTIONS)
        return run(args, client or make_client(), read)
    except Failure as failure:
        print(f"error: {failure.message}", file=sys.stderr)
        return failure.code
    except Exception as error:  # a Spidra error, a timeout or a failed crawl: say it in one line
        failure = failure_from(error)
        print(f"error: {failure.message}", file=sys.stderr)
        return failure.code

Save the pieces as ingest_docs.py and run python ingest_docs.py https://docs.example.com/docs/ --section /docs/ --out data --query "how do I log in". Add --crawl to crawl instead, --tests tests.json to score questions and --previous data/pages.jsonl to see what changed.

The exit code says what happened: 0 for success, 3 for the key, 4 for credits or an overdue payment, 5 for the rate limit, 10 when no page was ingested, 11 for bad options, and 12 when the dataset was written but some pages couldn't be fetched.

A docs dataset that stays current

You now have a way to turn a documentation site into a dataset with a reason for every page, clean text, code that survives chunking, a source URL on every chunk, and a retrieval test to prove it. A retrieval assistant is only as good as that foundation, and the foundation has to be rebuilt every time the docs change.

Here is what Spidra gives you for that job:

  • Map, then fetch only what you chose. One request lists a site's URLs from its sitemap and links, ranked by a search, so you pay to fetch the pages you want and not the ones you don't.
  • Cleaner Markdown from batch scrape. Content-only mode strips navigation, headers, footers and sidebars on up to 50 pages per batch, with a result for each page.
  • Crawl when you can't list the pages. Describe the pages you want, and read a report that says what it understood and what it skipped, with a reason for each.
  • Respect for the site. Map and Crawl can honor robots.txt, so a recurring ingestion stays polite.
  • Failures that are visible. Each page has its own status, and a failed page is free, so a partial run is a plan and not a mystery.
  • One account for the whole pipeline. Search to find the docs, Map to see them, batch scrape or Crawl to read them, and Parse for the PDFs on the same site.

A docs assistant that answers from last year's pages is worse than none. Spidra won't write the chunking policy or choose your embeddings for you, and this tutorial doesn't pretend it does. It gives you the part that has to be reliable on every run: the pages, cleanly, with their URLs.

Create a free account, point ingest_docs.py at a documentation site your product depends on, and read the manifest. Our Map then batch scrape post covers the first half in more depth, the batch scrape docs list every option, and the guides include a RAG walkthrough.

Frequently asked questions

Map the site to see its pages, choose the ones you want and record why you skip the others, fetch their Markdown, clean it, split it by heading without cutting code blocks, and store each chunk with its source URL and title. Then test retrieval with real questions before you rely on it.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.