{"slug": "how-to-crawl-a-documentation-website-for-rag", "title": "How to crawl a documentation website for RAG", "summary": "A tutorial published on the Spidra documentation site outlines a seven-step pipeline for crawling documentation websites into retrieval-augmented generation datasets, using Spidra's Map endpoint to list URLs before scraping. In a real run against the FastAPI docs, Map matched 36 URLs about dependencies out of 619 scanned, and three of the first five results were German, Spanish and French copies of one reference page — the duplication and language-mixing problem the pipeline's selection step is designed to filter out. The tutorial's steps are map, select, fetch, clean, chunk by heading without splitting code blocks, store chunks with source URL, title and heading path, and test retrieval before trusting it.", "body_md": "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.\n\nThis 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.\n\nInstall the packages and put your Spidra key in the environment as `SPIDRA_API_KEY`:\n\n``` python\n# pip install spidra httpx rank-bm25 snowballstemmer\nimport argparse\nimport hashlib\nimport json\nimport os\nimport re\nimport sys\nimport time\n\nfrom collections import Counter\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom fnmatch import fnmatch\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom urllib.parse import parse_qsl, urlencode, urlsplit\n\nimport httpx\nfrom rank_bm25 import BM25Okapi\nfrom snowballstemmer import stemmer\npython\nfrom spidra import (\n    CrawlParams,\n    Spidra,\n    SpidraAuthenticationError,\n    SpidraError,\n    SpidraJobFailedError,\n    SpidraPaymentRequiredError,\n    SpidraRateLimitError,\n    SpidraServerError,\n    SpidraTimeoutError,\n    SpidraValidationError,\n)\n```\n\n## The plan\n\nSeven steps turn a site into a dataset, and each one answers a failure you'd otherwise find later:\n\n1. **Map** the site to see every page it exposes.\n2. **Select** the pages worth ingesting, and record why each other page was skipped.\n3. **Fetch** the Markdown, with failures reported instead of hidden.\n4. **Clean** it: navigation, anchors and site names out.\n5. **Chunk** it by heading, without cutting a code block.\n6. **Store** the chunks with their source URL, title and heading path.\n7. **Test** retrieval before you trust it.\n\n## See the site first with Map\n\n[Map](https://docs.spidra.io/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:\n\n```\n# needs SPIDRA_API_KEY\nclient = Spidra(api_key=os.environ[\"SPIDRA_API_KEY\"])\nsite = client.map(\"https://docs.python.org/3/\", search=\"asyncio\", limit=20)\nprint(site.total, \"matched,\", site.scanned, \"scanned\")\nfor link in site.links[:3]:\n    print(link.url, \"|\", link.title)\n```\n\nOutput:\n\n```\n21 matched, 556 scanned\nhttps://docs.python.org/3/library/asyncio.html | asyncio\nhttps://docs.python.org/3/library/asyncio-threading.html | asyncio and free-threaded Python\nhttps://docs.python.org/3/howto/a-conceptual-overview-of-asyncio.html | A conceptual overview of asyncio\n```\n\nThis 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.\n\nMap shows what a site exposes, and what it exposes isn't always what you want. Here is a real run on the FastAPI docs:\n\n```\n# needs SPIDRA_API_KEY\nsite = client.map(\"https://fastapi.tiangolo.com/\", search=\"dependencies\", limit=10)\nprint(site.total, \"URLs matched,\", site.scanned, \"scanned\")\nfor link in site.links[:5]:\n    print(link.url)\n```\n\nOutput:\n\n```\n36 URLs matched, 619 scanned\nhttps://fastapi.tiangolo.com/tutorial/dependencies/\nhttps://fastapi.tiangolo.com/reference/dependencies/\nhttps://fastapi.tiangolo.com/de/reference/dependencies/\nhttps://fastapi.tiangolo.com/es/reference/dependencies/\nhttps://fastapi.tiangolo.com/fr/reference/dependencies/\n```\n\nThree 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.\n\n## A docs site to practice on\n\nTo 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:\n\n```\nBASE = \"https://docs.example.test\"\nFENCE = \"`\" * 3\nTOP = \"[Skip to content](#main)\\n\\n* [Docs](https://spidra.io/docs/)\\n* [Sign in](https://spidra.io/login)\\n\\n\"\nEND = \"\\nWas this page helpful?\\n\\n© 2026 Example, Inc. All rights reserved.\\n\"\nAUTH = \"# Authentication [¶](#authentication)\\n\\nEvery request needs an API key. Send it in \"\nAUTH += \"the `Authorization` header as a bearer token. Without a valid key, a request fails.\\n\"\nAUTH += \"\\n## Rotating keys [¶](#rotating)\\n\\nCreate a new key, deploy it, then revoke the old \"\nAUTH += \"one. Both keys work during the overlap, so a rotation never needs downtime.\\n\"\nRATE = \"# Rate limits [¶](#rate)\\n\\nEach key can send 60 requests a minute. Over that, the API \"\nRATE += \"answers with the status code 429 and a `Retry-After` header that says how long to wait.\\n\"\npython\nLOOP = \"def iter_notes(client):\\n    cursor = None\\n    while True:\\n\"\nLOOP += \"        page = client.list(cursor)\\n        yield from page.items\\n\"\nLOOP += \"        cursor = page.next_cursor\\n        if not cursor:\\n            return\"\nINTRO = \"# Pagination [¶](#pagination)\\n\\nPass `next_cursor` back until it is empty.\\n\\n\"\nPAGES = {\"/docs/authentication\": AUTH, \"/docs/rate-limits\": RATE}\nPAGES[\"/docs/pagination\"] = f\"{INTRO}{FENCE}python\\n{LOOP}\\n{FENCE}\\n\"\nPAGES[\"/docs/de/authentication\"] = \"# Authentifizierung\\n\\nSenden Sie Ihren Schlüssel im Header.\\n\"\nPAGES[\"/docs/v1/pagination\"] = \"# Pagination (v1)\\n\\nVersion 1 used page numbers.\\n\"\nTOPICS = {\n    \"errors\": (\"Errors\", \"A 401 means the API key is missing or invalid, and a 404 means \"\n               \"the note does not exist. Retry 429 and 5xx with exponential backoff.\"),\n    \"webhooks\": (\"Webhooks\", \"The API calls your server when a note is created. Each call is \"\n                 \"signed, so verify the signature header against your signing secret.\"),\n    \"sdk-python\": (\"Python SDK\", \"Install the client with pip. It needs Python 3.9 or newer, \"\n                   \"and every method takes a timeout in seconds. A timeout raises an \"\n                   \"error that you can catch and retry.\"),\n    \"getting-started\": (\"Getting started\", \"Create an account, copy your API key and install \"\n                        \"the client. Then create your first note and read it back by its id. \"\n                        \"Notes are private to your account.\"),\n}\nfor slug, (title, text) in TOPICS.items():\n    PAGES[f\"/docs/{slug}\"] = f\"# {title} [¶](#{slug})\\n\\n{text}\\n\"\npython\nclass TinyDocs:\n    def map(self, url, search=None, limit=500, respect_robots=False):\n        paths = [*PAGES, \"/docs/assets/diagram.png\", \"/pricing\"]\n        links = [SimpleNamespace(url=BASE + p, title=None) for p in paths]\n        return SimpleNamespace(links=links, total=len(links), scanned=len(links) + 30)\n\n    def batch_scrape(self, urls, output=\"markdown\", extract_content_only=False):\n        page = lambda u: PAGES[u[len(BASE) :]]\n        text = lambda u: page(u) if extract_content_only else TOP + page(u) + END\n        make = lambda u: SimpleNamespace(url=u, status=\"completed\", result=text(u), error=None)\n        return SimpleNamespace(items=[make(u) for u in urls])\n```\n\n## Choose pages, and keep the reasons\n\nA 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:\n\n```\nLOCALES = 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())\nVERSION = re.compile(r\"^v?\\d+(\\.\\d+)*$\", re.I)\nFILE_TYPES = tuple(\".\" + e for e in \"png jpg jpeg gif svg webp pdf zip gz mp4 css js\".split())\nTRACKING = re.compile(r\"^(utm_.+|gclid|fbclid)$\", re.I)\n\ndef page_key(url):\n    \"\"\"One key per page: host, path without a trailing slash, query without tracking.\"\"\"\n    parts = urlsplit(url.strip())\n    query = urlencode(sorted(q for q in parse_qsl(parts.query) if not TRACKING.match(q[0])))\n    return f\"{(parts.hostname or '').lower()}{parts.path.rstrip('/')}\" + (\n        f\"?{query}\" if query else \"\"\n    )\npython\ndef segments(path):\n    \"\"\"The lowercase parts of a URL path, without the empty ones.\"\"\"\n    return [s.lower() for s in path.split(\"/\") if s]\npython\ndef skip_reason(url, section, exclude=()):\n    \"\"\"Why a URL is left out, or an empty string to keep it. The first rule that matches wins.\"\"\"\n    path = urlsplit(url).path\n    base, found = segments(section), segments(path)\n    extra = found[len(base) :] if found[: len(base)] == base else []\n    if found[: len(base)] != base:\n        return \"outside_section\"\n    if path.lower().endswith(FILE_TYPES):\n        return \"file_type\"\n    if any(s in LOCALES for s in extra):\n        return \"translated\"\n    if any(VERSION.match(s) for s in extra):\n        return \"other_version\"\n    return \"excluded\" if any(fnmatch(path, pattern) for pattern in exclude) else \"\"\npython\ndef select_pages(links, section, exclude=()):\n    \"\"\"Split mapped links into pages to fetch and pages skipped, each skip with its reason.\"\"\"\n    kept, skipped, seen = [], [], set()\n    for link in links:\n        reason = skip_reason(link.url, section, exclude) or (\n            \"duplicate\" if page_key(link.url) in seen else \"\"\n        )\n        seen.add(page_key(link.url))\n        (skipped if reason else kept).append(\n            {\"url\": link.url, \"title\": link.title, **({\"reason\": reason} if reason else {})}\n        )\n    return kept, skipped\npython\ndef count_reasons(skipped):\n    \"\"\"How many pages were skipped for each reason, the most common reason first.\"\"\"\n    return dict(Counter(row[\"reason\"] for row in skipped).most_common())\n```\n\n`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.\n\n```\nclient = TinyDocs()\nsite = client.map(BASE + \"/docs/\")\nkeep, skipped = select_pages(site.links, \"/docs/\")\nprint(\"keep:\", [k[\"url\"].replace(BASE, \"\") for k in keep])\nfor row in skipped:\n    print(\"skip:\", row[\"url\"].replace(BASE, \"\"), \"->\", row[\"reason\"])\n```\n\nOutput:\n\n```\nkeep: ['/docs/authentication', '/docs/rate-limits', '/docs/pagination', '/docs/errors', '/docs/webhooks', '/docs/sdk-python', '/docs/getting-started']\nskip: /docs/de/authentication -> translated\nskip: /docs/v1/pagination -> other_version\nskip: /docs/assets/diagram.png -> file_type\nskip: /pricing -> outside_section\n```\n\nSeven 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.\n\n## Fetch the Markdown\n\nYou 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:\n\n```\n@dataclass\nclass Page:\n    url: str\n    title: str\n    markdown: str\n    source: str  # \"batch\" or \"crawl\"\n    status: str = \"ok\"  # \"ok\" or \"failed\"\n    error: str = \"\"\npython\ndef page_from_item(item, titles):\n    ok = item.status == \"completed\" and bool(item.result)\n    error = \"\" if ok else str(item.error or item.status)\n    return Page(\n        item.url,\n        titles.get(item.url) or \"\",\n        item.result if ok else \"\",\n        \"batch\",\n        \"ok\" if ok else \"failed\",\n        error,\n    )\npython\ndef batch_pages(client, urls, titles):\n    \"\"\"One batch of up to 50 URLs. It says completed even if items failed, so check each.\"\"\"\n    batch = client.batch_scrape(urls, output=\"markdown\", extract_content_only=True)\n    return [page_from_item(item, titles) for item in batch.items]\npython\ndef fetch_batch(client, urls, titles=None, size=50, retries=1):\n    \"\"\"Fetch in groups of 50, then give the failed ones another go.\"\"\"\n    titles, done, todo = titles or {}, {}, list(urls)\n    for _ in range(retries + 1):\n        for start in range(0, len(todo), size):\n            for page in batch_pages(client, todo[start : start + size], titles):\n                done[page.url] = page\n        todo = [u for u in urls if done.get(u) is None or done[u].status == \"failed\"]\n        if not todo:\n            break\n    return [done[u] for u in urls if u in done]\n```\n\n`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.\n\n```\npages = fetch_batch(client, [k[\"url\"] for k in keep])\nfor p in pages:\n    print(p.status, p.url.replace(BASE, \"\"), len(p.markdown), \"characters\")\n```\n\nOutput:\n\n```\nok /docs/authentication 325 characters\nok /docs/rate-limits 173 characters\nok /docs/pagination 288 characters\nok /docs/errors 155 characters\nok /docs/webhooks 158 characters\nok /docs/sdk-python 191 characters\nok /docs/getting-started 193 characters\n```\n\n### Or crawl\n\nIf you can't list the pages, [Crawl](https://docs.spidra.io/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:\n\n```\n# needs SPIDRA_API_KEY\njob = client.crawl(CrawlParams(\n    base_url=\"https://docs.python.org/3/library/asyncio.html\",\n    crawl_instruction=\"Individual Python asyncio reference pages\",\n    crawl_entire_domain=True, include_paths=[\"/3/library/asyncio*\"], max_pages=5,\n))\nfor page in job.result:\n    markdown = httpx.get(page.markdown, timeout=30).text\n    print(page.url.rsplit(\"/\", 1)[-1], len(markdown), \"characters\", markdown.count(\"Output:\n\n```\nasyncio-runner.html 10407 characters 2 code blocks\nasyncio-task.html 59841 characters 32 code blocks\nasyncio-stream.html 22038 characters 11 code blocks\nasyncio-subprocess.html 17414 characters 4 code blocks\nasyncio-queue.html 11371 characters 1 code blocks\n```\n\nThe 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:\n\n``` python\ndef download(link):\n    \"\"\"Crawl results hold a signed link that expires, so read it right away.\"\"\"\n    response = httpx.get(link, timeout=30)\n    response.raise_for_status()\n    return response.text\npython\ndef wait_for_crawl(client, job_id, poll=3.0, timeout=600.0, sleep=time.sleep):\n    waited = 0.0\n    while waited <= timeout:\n        state = client.get_crawl(job_id)\n        if state.status == \"completed\":\n            return state\n        if state.status in (\"failed\", \"cancelled\"):\n            raise RuntimeError(\n                f\"the crawl {state.status}: {getattr(state, 'error', '') or ''}\".strip()\n            )\n        sleep(poll)\n        waited += poll\n    raise TimeoutError(\"the crawl did not finish in time\")\npython\ndef crawl_pages(state, read):\n    \"\"\"The pages a crawl returned, with each Markdown link read straight away.\"\"\"\n    pages = []\n    for item in state.result:\n        try:\n            pages.append(Page(item.url, item.title or \"\", read(item.markdown), \"crawl\"))\n        except (httpx.HTTPError, OSError) as error:\n            pages.append(Page(item.url, item.title or \"\", \"\", \"crawl\", \"failed\", str(error)))\n    return pages\npython\ndef start_params(start_url, include_paths, max_pages):\n    return CrawlParams(\n        base_url=start_url,\n        crawl_instruction=\"Individual documentation pages\",\n        crawl_entire_domain=True,\n        include_paths=include_paths,\n        max_pages=max_pages,\n        respect_robots=True,\n    )\npython\ndef fetch_crawl(\n    client, start_url, include_paths, max_pages=50, read=download, poll=3.0, sleep=time.sleep\n):\n    \"\"\"Crawl instead of map and batch. Returns the pages and the crawl's own report.\"\"\"\n    job_id = client.start_crawl(start_params(start_url, include_paths, max_pages)).job_id\n    state = wait_for_crawl(client, job_id, poll, sleep=sleep)\n    return crawl_pages(state, read), crawl_report(client, job_id)\npython\ndef crawl_report(client, job_id):\n    \"\"\"What the crawl understood, how many pages it only read, and what it skipped.\"\"\"\n    report = client.crawl_report(job_id).report\n    skipped = {row.reason: row.count for row in report.skipped}\n    return {\n        \"understood_as\": report.understood_as,\n        \"navigation_pages\": report.navigation_pages,\n        \"skipped_total\": report.skipped_total,\n        \"skipped\": skipped,\n    }\n```\n\nThe 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`.\n\n## Know where the code is\n\nCleaning 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:\n\n``` python\nOPENING = re.compile(r\"^ {0,3}(`{3,}|~{3,})([^`]*)$\")\n\ndef closes(line, marker):\n    \"\"\"A closing fence is only fence characters, at least as many as the opening one.\"\"\"\n    text = line.strip()\n    return len(text) >= len(marker) and text == text[0] * len(text) and text[0] == marker[0]\npython\ndef walk(markdown):\n    \"\"\"Yield (line, in_code) for every line. The fence lines themselves count as code.\"\"\"\n    marker = \"\"\n    for line in markdown.splitlines():\n        opening = None if marker else OPENING.match(line)\n        if marker:\n            yield line, True\n            marker = \"\" if closes(line, marker) else marker\n        elif opening:\n            marker = opening.group(1)\n            yield line, True\n        else:\n            yield line, False\ntext = f\"before\\n{FENCE}python\\n# not a heading\\n  x = 1\\n{FENCE}\\nafter\"\nfor line, in_code in walk(text):\n    print(in_code, repr(line))\n```\n\nOutput:\n\n```\nFalse 'before'\nTrue '``` python'\nTrue '# not a heading'\nTrue '  x = 1'\nTrue '```'\nFalse 'after'\n```\n\n`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.\n\n## Clean the Markdown\n\nA 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:\n\n```\nHEADING = re.compile(r\"^(#{1,6})\\s+(.*?)\\s*#*\\s*$\")\nPERMALINK = re.compile(r\"\\s*\\[(?:¶|#|[Pp]ermalink[^\\]]*)?\\]\\(#[^)]*\\)\")\nANCHOR_LABEL = re.compile(r\"\\[([^\\]]+)\\]\\(#[^)]*\\)\")\nLINK_ONLY = re.compile(r\"^\\s*(?:[*+-]|\\d+\\.)?\\s*(?:\\[[^\\]]*\\]\\([^)]*\\)[\\s|,·•-]*)+$\")\nPAGER = re.compile(r\"^\\s*\\[?\\s*(?:←|→|«|»)?\\s*(?:Previous|Next)\\b\", re.I)\nSEPARATORS = (\" | \", \" - \", \" – \", \" — \")\n\ndef clean_heading(line):\n    \"\"\"'### [Coroutines](#id2)' becomes '### Coroutines', and a trailing [¶](#x) disappears.\"\"\"\n    found = HEADING.match(line)\n    if not found:\n        return line\n    text = ANCHOR_LABEL.sub(r\"\\1\", PERMALINK.sub(\"\", found.group(2)))\n    return f\"{found.group(1)} {text.strip()}\"\npython\ndef strip_anchors(markdown):\n    \"\"\"Clean every heading outside a code block, and leave the code alone.\"\"\"\n    lines = [line if in_code else clean_heading(line) for line, in_code in walk(markdown)]\n    return \"\\n\".join(lines)\npython\ndef is_candidate(line):\n    \"\"\"Lines that can be page chrome: link-only lines or very short plain lines, never headings.\"\"\"\n    text = line.strip()\n    return (\n        bool(text) and not text.startswith(\"#\") and (bool(LINK_ONLY.match(line)) or len(text) <= 60)\n    )\n\ndef lines_outside_code(markdown):\n    return [line.strip() for line, in_code in walk(markdown) if not in_code and is_candidate(line)]\npython\ndef find_boilerplate(pages, min_share=0.6, min_pages=3):\n    \"\"\"Lines that repeat on most pages are the site's chrome, so they aren't documentation.\"\"\"\n    if len(pages) < min_pages:\n        return set()\n    counts = Counter(line for page in pages for line in set(lines_outside_code(page)))\n    return {line for line, seen in counts.items() if seen / len(pages) >= min_share}\n\ndef is_pager(line):\n    \"\"\"'[Previous: Pagination](https://spidra.io/docs/pagination)' is chrome too, though it differs on every page.\"\"\"\n    return bool(PAGER.match(line) and LINK_ONLY.match(line))\npython\ndef drop_lines(markdown, boilerplate):\n    kept = [\n        line\n        for line, in_code in walk(markdown)\n        if in_code or not (line.strip() in boilerplate or is_pager(line))\n    ]\n    return \"\\n\".join(kept)\npython\ndef tidy(markdown):\n    \"\"\"Trim trailing spaces and collapse runs of blank lines, but never inside a code block.\"\"\"\n    out, blank = [], 0\n    for line, in_code in walk(markdown):\n        blank = 0 if (in_code or line.strip()) else blank + 1\n        if in_code or blank <= 1:\n            out.append(line if in_code else line.rstrip())\n    return \"\\n\".join(out).strip(\"\\n\") + \"\\n\"\n\ndef clean_markdown(markdown, boilerplate=frozenset()):\n    return tidy(drop_lines(strip_anchors(markdown), boilerplate))\npython\ndef content_chars(markdown):\n    \"\"\"Characters of real content: prose and code, but not headings or link lists.\"\"\"\n    return sum(len(line.strip()) for line, in_code in walk(markdown) if in_code or is_prose(line))\n\ndef is_prose(line):\n    return bool(line.strip()) and not line.lstrip().startswith(\"#\") and not LINK_ONLY.match(line)\npython\ndef common_suffix(titles, min_share=0.6):\n    \"\"\"The site name that most titles end with, such as ' | Quillbase Docs'. Empty if none.\"\"\"\n    ends = [s + t.rpartition(s)[2] for t in titles for s in SEPARATORS if s in t]\n    if len(titles) < 2 or not ends:\n        return \"\"\n    suffix, seen = Counter(ends).most_common(1)[0]\n    return suffix if seen / len(titles) >= min_share else \"\"\n\ndef clean_title(title, suffix):\n    \"\"\"The title without the site name. A missing title (None) becomes an empty one.\"\"\"\n    title = (title or \"\").strip()\n    return title[: -len(suffix)].strip() if suffix and title.endswith(suffix) else title\npython\ndef first_heading(markdown):\n    \"\"\"The first level-1 heading outside a code block, for pages that arrive without a title.\"\"\"\n    for line, in_code in walk(markdown):\n        found = None if in_code else HEADING.match(line)\n        if found and len(found.group(1)) == 1:\n            return found.group(2).strip()\n    return \"\"\n```\n\n`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.\n\n```\npaths = [\"/docs/authentication\", \"/docs/pagination\", \"/docs/rate-limits\"]\nraw = [client.batch_scrape([BASE + p]).items[0].result for p in paths]\nboiler = find_boilerplate(raw)\nprint(raw[0].strip(), \"\\n\\n--- cleaned ---\\n\")\nprint(clean_markdown(raw[0], boiler))\n```\n\nOutput:\n\n```\n[Skip to content](#main)\n\n* [Docs](https://spidra.io/docs/)\n* [Sign in](https://spidra.io/login)\n\n# Authentication [¶](#authentication)\n\nEvery request needs an API key. Send it in the `Authorization` header as a bearer token. Without a valid key, a request fails.\n\n## Rotating keys [¶](#rotating)\n\nCreate a new key, deploy it, then revoke the old one. Both keys work during the overlap, so a rotation never needs downtime.\n\nWas this page helpful?\n\n© 2026 Example, Inc. All rights reserved. \n\n--- cleaned ---\n\n# Authentication\n\nEvery request needs an API key. Send it in the `Authorization` header as a bearer token. Without a valid key, a request fails.\n\n## Rotating keys\n\nCreate a new key, deploy it, then revoke the old one. Both keys work during the overlap, so a rotation never needs downtime.\n```\n\nMenu 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.\n\n## Chunk without breaking code\n\nChunking 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.\n\nThe 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:\n\n``` python\nSENTENCE = re.compile(r\"(?<=[.!?])\\s+\")\n\ndef sections(markdown, max_level=4):\n    \"\"\"(heading path, lines) for each section. A heading only counts outside a code block.\"\"\"\n    stack, lines, out = [], [], []\n    for line, in_code in walk(markdown):\n        found = None if in_code else HEADING.match(line)\n        if found and len(found.group(1)) <= max_level:\n            out.append(([text for _, text in stack], lines))\n            level = len(found.group(1))\n            stack = [(lv, t) for lv, t in stack if lv < level] + [(level, found.group(2))]\n            lines = []\n        lines.append(line)\n    return out + [([text for _, text in stack], lines)]\npython\ndef blocks(lines):\n    \"\"\"Paragraphs and whole code blocks. A code block is never broken up here.\"\"\"\n    out, buf, in_block = [], [], False\n    for line, in_code in walk(\"\\n\".join(lines)):\n        if in_code != in_block or (not in_code and not line.strip()):\n            out += [\"\\n\".join(buf)] if any(x.strip() for x in buf) else []\n            buf, in_block = [], in_code\n        if in_code or line.strip():\n            buf.append(line)\n    return out + ([\"\\n\".join(buf)] if any(x.strip() for x in buf) else [])\npython\ndef split_code(block, limit):\n    \"\"\"Cut an oversized code block between lines, and close and reopen its fence each time.\"\"\"\n    rows = block.split(\"\\n\")\n    opener = rows[0]\n    marker = OPENING.match(opener).group(1)\n    body = rows[1:-1] if closes(rows[-1], marker) and len(rows) > 1 else rows[1:]\n    room = max(limit - len(opener) - len(marker) - 2, 1)\n    parts, cur = [], []\n    for row in body:\n        if cur and sum(len(r) + 1 for r in cur) + len(row) > room:\n            parts.append(cur)\n            cur = []\n        cur.append(row)\n    parts.append(cur)\n    return [\"\\n\".join([opener, *part, marker]) for part in parts]\npython\ndef split_text(text, limit):\n    \"\"\"Cut a long paragraph at sentence ends, and at spaces only when a sentence is too long.\"\"\"\n    pieces, cur = [], \"\"\n    for sentence in SENTENCE.split(text):\n        for word_run in (\n            [sentence]\n            if len(sentence) <= limit\n            else re.findall(r\".{1,%d}(?:\\s+|$)\" % limit, sentence)\n        ):\n            if cur and len(cur) + 1 + len(word_run) > limit:\n                pieces.append(cur)\n                cur = \"\"\n            cur = f\"{cur} {word_run}\".strip()\n    return pieces + [cur]\npython\ndef fit(block, limit):\n    if len(block) <= limit:\n        return [block]\n    return (\n        split_code(block, limit)\n        if OPENING.match(block.split(\"\\n\")[0])\n        else split_text(block, limit)\n    )\npython\ndef pack(parts, limit):\n    \"\"\"Fill each chunk with whole blocks until the next one would not fit.\"\"\"\n    chunks, cur = [], \"\"\n    for block in (piece for part in parts for piece in fit(part, limit)):\n        if cur and len(cur) + 2 + len(block) > limit:\n            chunks.append(cur)\n            cur = \"\"\n        cur = f\"{cur}\\n\\n{block}\" if cur else block\n    return chunks + ([cur] if cur else [])\n\ndef chunk_id(url, path, text):\n    return hashlib.sha1(f\"{url}|{' > '.join(path)}|{text}\".encode(\"utf-8\")).hexdigest()[:12]\npython\ndef has_body(parts):\n    return any(not HEADING.match(p) for p in parts)\n\ndef make_chunk(url, title, path, text, index):\n    return {\n        \"id\": chunk_id(url, path, text),\n        \"url\": url,\n        \"title\": title,\n        \"heading_path\": path,\n        \"index\": index,\n        \"text\": text,\n    }\npython\ndef chunk_page(url, title, markdown, max_chars=1200):\n    \"\"\"One dict per chunk, with the source URL, title and heading path that produced it.\"\"\"\n    out = []\n    for path, lines in sections(markdown):\n        parts = blocks(lines)\n        for text in pack(parts, max_chars) if has_body(parts) else []:\n            out.append(make_chunk(url, title, path, text, len(out)))\n    return out\n\ndef embed_text(chunk):\n    \"\"\"What to embed or index: the breadcrumb tells a chunk which page and section it came from.\"\"\"\n    return \" > \".join([chunk[\"title\"], *chunk[\"heading_path\"]]) + \"\\n\\n\" + chunk[\"text\"]\n```\n\n`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.\n\n```\ntext = clean_markdown(PAGES[\"/docs/pagination\"])\nfor c in chunk_page(BASE + \"/docs/pagination\", \"Pagination\", text, max_chars=160):\n    print(c[\"heading_path\"], len(c[\"text\"]), \"chars,\", c[\"text\"].count(FENCE), \"fence marks\")\nprint(c[\"text\"])\n```\n\nOutput:\n\n```\n['Pagination'] 56 chars, 0 fence marks\n['Pagination'] 136 chars, 2 fence marks\n['Pagination'] 89 chars, 2 fence marks\n``` python\n        cursor = page.next_cursor\n        if not cursor:\n            return\nAt 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.\n\n## Store the dataset with its provenance\n\nThe 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:\n\n``` python\ndef utc_now():\n    return datetime.now(timezone.utc)\n\ndef page_hash(markdown):\n    return hashlib.sha1(markdown.encode(\"utf-8\")).hexdigest()[:16]\n\ndef map_site(client, url, search=None, limit=500):\n    \"\"\"Every URL Map can see. robots.txt is respected, because the default is not to.\"\"\"\n    return client.map(url, search=search, limit=limit, respect_robots=True)\n\ndef slug_title(url):\n    return url.rstrip(\"/\").rsplit(\"/\", 1)[-1].replace(\"-\", \" \").replace(\"_\", \" \").capitalize()\npython\ndef title_for(page, clean, suffix):\n    \"\"\"The title without the site name. Map gives none for sitemap-only URLs, so fall back.\"\"\"\n    return clean_title(page.title, suffix) or first_heading(clean) or slug_title(page.url)\n\ndef clean_pages(pages):\n    \"\"\"Clean every page. Lines that repeat across the whole set are found first.\"\"\"\n    ok = [p for p in pages if p.status == \"ok\"]\n    boiler = find_boilerplate([p.markdown for p in ok])\n    suffix = common_suffix([p.title for p in ok if p.title])\n    cleaned = [(p, clean_markdown(p.markdown, boiler)) for p in ok]\n    return [(p, clean, title_for(p, clean, suffix)) for p, clean in cleaned]\npython\ndef skipped_row(url, reason, title=\"\"):\n    \"\"\"A manifest row for a page that was left out, and why.\"\"\"\n    return {\"url\": url, \"title\": title, \"status\": \"skipped\", \"reason\": reason}\npython\ndef included_row(page, clean, title, count, now):\n    sizes = {\"raw_chars\": len(page.markdown), \"clean_chars\": len(clean), \"chunks\": count}\n    return {\n        \"url\": page.url,\n        \"title\": title,\n        \"status\": \"included\",\n        \"reason\": \"\",\n        \"source\": page.source,\n        **sizes,\n        \"page_hash\": page_hash(clean),\n        \"fetched_at\": now.isoformat(),\n    }\npython\ndef failed_row(page):\n    return {\n        \"url\": page.url,\n        \"title\": page.title,\n        \"status\": \"failed\",\n        \"reason\": \"fetch_failed\",\n        \"error\": page.error,\n    }\npython\ndef one_page(page, clean, title, max_chars, min_content, now):\n    \"\"\"A page's manifest row and its chunks. A page with too little real content is skipped.\"\"\"\n    pieces = (\n        chunk_page(page.url, title, clean, max_chars) if content_chars(clean) >= min_content else []\n    )\n    return (\n        included_row(page, clean, title, len(pieces), now)\n        if pieces\n        else skipped_row(page.url, \"too_little_text\", title)\n    ), pieces\npython\ndef page_rows(pages, max_chars, min_content, now):\n    rows, chunks = [], []\n    for page, clean, title in clean_pages(pages):\n        row, pieces = one_page(page, clean, title, max_chars, min_content, now)\n        rows.append(row)\n        chunks += pieces\n    return rows, chunks\n\ndef build_dataset(pages, skipped=(), max_chars=1200, min_content=120, clock=utc_now):\n    \"\"\"Turn fetched pages into manifest rows and chunks. Nothing is dropped without a reason.\"\"\"\n    rows = [skipped_row(s[\"url\"], s[\"reason\"], s.get(\"title\", \"\")) for s in skipped]\n    rows += [failed_row(p) for p in pages if p.status == \"failed\"]\n    more, chunks = page_rows(pages, max_chars, min_content, clock())\n    return {\"pages\": rows + more, \"chunks\": chunks}\npython\ndef summarize(dataset):\n    rows = dataset[\"pages\"]\n    left_out = [r for r in rows if r[\"status\"] != \"included\"]\n    return {\n        \"included\": len(rows) - len(left_out),\n        \"chunks\": len(dataset[\"chunks\"]),\n        \"failed\": sum(r[\"status\"] == \"failed\" for r in rows),\n        \"skipped\": count_reasons([r for r in left_out if r[\"status\"] == \"skipped\"]),\n    }\npython\ndef ingest_batch(\n    client, url, section, search=None, limit=500, exclude=(), max_chars=1200, clock=utc_now\n):\n    \"\"\"Map, choose, batch scrape, clean, chunk. The mapped URLs and the skips come back too.\"\"\"\n    site = map_site(client, url, search, limit)\n    keep, skipped = select_pages(site.links, section, exclude)\n    pages = fetch_batch(client, [k[\"url\"] for k in keep], {k[\"url\"]: k[\"title\"] for k in keep})\n    return {\n        **build_dataset(pages, skipped, max_chars, clock=clock),\n        \"mapped\": len(site.links),\n        \"scanned\": site.scanned,\n    }\npython\ndef ingest_crawl(\n    client, start_url, include_paths, max_pages=50, max_chars=1200, read=None, clock=utc_now\n):\n    \"\"\"Crawl instead. The crawl's own report says what it skipped.\"\"\"\n    kwargs = {\"read\": read} if read else {}\n    pages, report = fetch_crawl(client, start_url, include_paths, max_pages, **kwargs)\n    return {**build_dataset(pages, (), max_chars, clock=clock), \"crawl_report\": report}\npython\ndef write_jsonl(path, rows):\n    with open(path, \"w\", encoding=\"utf-8\") as handle:\n        handle.writelines(json.dumps(row, ensure_ascii=False) + \"\\n\" for row in rows)\n\ndef read_jsonl(path):\n    lines = Path(path).read_text(encoding=\"utf-8\").splitlines()\n    return [json.loads(line) for line in lines if line.strip()]\n\ndef save_dataset(dataset, folder):\n    \"\"\"pages.jsonl has a row for every page, included or not. chunks.jsonl has the text.\"\"\"\n    Path(folder).mkdir(parents=True, exist_ok=True)\n    write_jsonl(Path(folder) / \"pages.jsonl\", dataset[\"pages\"])\n    write_jsonl(Path(folder) / \"chunks.jsonl\", dataset[\"chunks\"])\npython\ndef diff_manifests(old, new):\n    \"\"\"Compare two runs by page hash: what is new, gone, changed, or the same.\"\"\"\n    before = {r[\"url\"]: r[\"page_hash\"] for r in old if r.get(\"page_hash\")}\n    after = {r[\"url\"]: r[\"page_hash\"] for r in new if r.get(\"page_hash\")}\n    return {\n        \"added\": sorted(set(after) - set(before)),\n        \"removed\": sorted(set(before) - set(after)),\n        \"changed\": sorted(u for u in after if u in before and after[u] != before[u]),\n        \"unchanged\": sorted(u for u in after if u in before and after[u] == before[u]),\n    }\n```\n\n`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.\n\n```\ndataset = ingest_batch(client, BASE + \"/docs/\", \"/docs/\")\nprint(summarize(dataset))\nchunk = dataset[\"chunks\"][1]\nprint(json.dumps({k: chunk[k] for k in (\"id\", \"url\", \"title\", \"heading_path\")}, indent=2))\n```\n\nOutput:\n\n```\n{'included': 7, 'chunks': 8, 'failed': 0, 'skipped': {'translated': 1, 'other_version': 1, 'file_type': 1, 'outside_section': 1}}\n{\n  \"id\": \"f022ee44be0e\",\n  \"url\": \"https://docs.example.test/docs/authentication\",\n  \"title\": \"Authentication\",\n  \"heading_path\": [\n    \"Authentication\",\n    \"Rotating keys\"\n  ]\n}\n```\n\nEvery chunk can be traced to a clean URL, a title and a heading path, and no heading carries an anchor.\n\n## Test retrieval before you trust it\n\nA dataset isn't ready until questions find their pages. This test uses [BM25](https://en.wikipedia.org/wiki/Okapi_BM25), which needs no API key, with stemming so that \"authenticate\" finds \"authentication\". Swap in embeddings later and keep the same test questions:\n\n```\nSTEM = stemmer(\"english\").stemWord\nSTOP = set(\"a an and are as at be by can do does for from how i in is it\".split()) | set(\n    \"of on or that the to what when with you your\".split()\n)\n\ndef tokens(text):\n    \"\"\"Lowercase, stemmed words. A snake_case name is kept whole and also split into its parts.\"\"\"\n    words = re.findall(r\"[a-z0-9_]+\", text.lower())\n    parts = [w for word in words for w in ([word, *word.split(\"_\")] if \"_\" in word else [word])]\n    return [STEM(w) for w in parts if w and w not in STOP]\npython\nclass Index:\n    def __init__(self, chunks):\n        self.chunks = chunks\n        self.bm25 = BM25Okapi([tokens(embed_text(c)) for c in chunks])\n\n    def search(self, query, k=3):\n        scores = self.bm25.get_scores(tokens(query))\n        order = sorted(range(len(scores)), key=lambda i: (-scores[i], i))[:k]\n        return [\n            {\"score\": round(float(scores[i]), 2), **self.chunks[i]} for i in order if scores[i] > 0\n        ]\npython\ndef hit_rate(index, tests, k=3):\n    \"\"\"The share of test questions whose expected page shows up in the top k chunks.\"\"\"\n    misses = [(q, want) for q, want in tests if want not in {r[\"url\"] for r in index.search(q, k)}]\n    return {\n        \"asked\": len(tests),\n        \"hit\": len(tests) - len(misses),\n        \"rate\": (len(tests) - len(misses)) / len(tests) if tests else 0.0,\n        \"misses\": misses,\n    }\n```\n\n`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:\n\n```\nurls = [p.url for p in pages]\nraw = [Page(u, \"\", client.batch_scrape([u]).items[0].result, \"batch\") for u in urls]\nraw_index = Index([c for p in raw for c in chunk_page(p.url, p.title, p.markdown)])\nclean_index = Index(dataset[\"chunks\"])\nquestions = {\n    \"How do I authenticate requests?\": \"/docs/authentication\",\n    \"What is the rate limit?\": \"/docs/rate-limits\",\n    \"How do I get the next page of results?\": \"/docs/pagination\",\n    \"How do I verify a webhook?\": \"/docs/webhooks\",\n    \"How do I install the Python SDK?\": \"/docs/sdk-python\",\n}\ntests = [(question, BASE + path) for question, path in questions.items()]\nfor name, index in ((\"raw\", raw_index), (\"cleaned\", clean_index)):\n    found = hit_rate(index, tests, k=1)\n    print(name, f\"{found['hit']} of {found['asked']} questions found their page first\")\n```\n\nOutput:\n\n```\nraw 4 of 5 questions found their page first\ncleaned 5 of 5 questions found their page first\n```\n\nCleaned 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:\n\n``` python\ndef chrome(index):\n    hits = [h for q, _ in tests for h in index.search(q, 3)]\n    return sum(\"Skip to content\" in h[\"text\"] or \"helpful\" in h[\"text\"] for h in hits)\n\nprint(\"results carrying site chrome:\", chrome(raw_index), \"raw,\", chrome(clean_index), \"cleaned\")\nprint(\"first raw chunk:    \", repr(raw_index.chunks[0][\"text\"][:34]))\nprint(\"first cleaned chunk:\", repr(clean_index.chunks[0][\"text\"][:34]))\n```\n\nOutput:\n\n```\nresults carrying site chrome: 10 raw, 0 cleaned\nfirst raw chunk:     '[Skip to content](#main)\\n\\n* [Docs]'\nfirst cleaned chunk: '# Authentication\\n\\nEvery request ne'\n```\n\nTen 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.\n\nA 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.\n\n## Keep it fresh\n\nDocumentation 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.\n\n```\nbefore = dataset[\"pages\"]\nPAGES[\"/docs/rate-limits\"] += \"\\n## Headers\\n\\nEvery response carries `X-RateLimit-Remaining`.\\n\"\nafter = ingest_batch(client, BASE + \"/docs/\", \"/docs/\")[\"pages\"]\nprint({key: len(urls) for key, urls in diff_manifests(before, after).items()})\n```\n\nOutput:\n\n```\n{'added': 0, 'removed': 0, 'changed': 1, 'unchanged': 6}\n```\n\nOne 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.\n\n## The finished command\n\nThe 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:\n\n```\nNO_API_KEY = 3  # missing or rejected\nRULES = [\n    (\n        SpidraAuthenticationError,\n        NO_API_KEY,\n        \"the Spidra API key was rejected. Check SPIDRA_API_KEY.\",\n    ),\n    (SpidraPaymentRequiredError, 4, \"the account is out of credits, or its payment is overdue.\"),\n    (SpidraRateLimitError, 5, \"too many requests. Wait a moment and try again.\"),\n    (SpidraTimeoutError, 6, \"Spidra took too long to answer.\"),\n    (SpidraJobFailedError, 7, None),  # its own message says what failed\n    (SpidraValidationError, 8, None),  # its own message says which option was refused\n    (SpidraServerError, 9, \"Spidra had a problem on its side. Try again.\"),\n]\nUNKNOWN = 1\nNO_PAGES = 10  # nothing on the site matched\nBAD_OPTIONS = 11  # the options can't be used together\nSOME_FAILED = 12  # the dataset was written, but some pages could not be fetched\n\nclass Failure(Exception):\n    def __init__(self, message, code):\n        super().__init__(message)\n        self.message, self.code = message, code\npython\ndef explain(error):\n    \"\"\"The first rule that matches wins. List the specific errors before the general one.\"\"\"\n    for kind, code, text in RULES:\n        if isinstance(error, kind):\n            return Failure(text or str(error), code)\n    return Failure(str(error), UNKNOWN)\n\ndef failure_from(error):\n    return explain(error) if isinstance(error, SpidraError) else Failure(str(error), UNKNOWN)\npython\ndef split_list(text):\n    return [part.strip() for part in (text or \"\").split(\",\") if part.strip()]\n\ndef add_site_options(ask):\n    ask.add_argument(\"url\", help=\"a page on the docs site, such as its docs index\")\n    ask.add_argument(\"--section\", help=\"keep only pages under this path (default: the URL's path)\")\n    ask.add_argument(\"--search\", help=\"only URLs related to these words\")\n    ask.add_argument(\"--limit\", type=int, default=500, help=\"URLs to map, 1 to 5000\")\n    ask.add_argument(\"--exclude\", help=\"comma-separated path patterns to leave out\")\n    ask.add_argument(\"--crawl\", action=\"store_true\", help=\"crawl instead of map and batch scrape\")\n    ask.add_argument(\"--max-pages\", type=int, default=50, help=\"pages a crawl may return\")\npython\ndef build_parser():\n    ask = argparse.ArgumentParser(description=\"Turn a documentation site into a RAG-ready dataset.\")\n    add_site_options(ask)\n    ask.add_argument(\"--max-chars\", type=int, default=1200, help=\"largest chunk, in characters\")\n    ask.add_argument(\"--out\", default=\"data\", help=\"folder for pages.jsonl and chunks.jsonl\")\n    ask.add_argument(\"--query\", help=\"run a test search over the new chunks\")\n    ask.add_argument(\"--tests\", help=\"a JSON file of [{question, url}] to score retrieval\")\n    ask.add_argument(\"--previous\", help=\"an earlier pages.jsonl, to report what changed\")\n    return ask\n\ndef make_client():\n    if not os.environ.get(\"SPIDRA_API_KEY\"):\n        raise Failure(\"set SPIDRA_API_KEY to your Spidra key first.\", NO_API_KEY)\n    return Spidra(api_key=os.environ[\"SPIDRA_API_KEY\"], api_url=os.environ.get(\"SPIDRA_API_URL\"))\npython\ndef ingest(args, client, read):\n    section = args.section or urlsplit(args.url).path or \"/\"\n    if args.crawl:\n        return ingest_crawl(\n            client, args.url, [section.rstrip(\"/\") + \"*\"], args.max_pages, args.max_chars, read\n        )\n    return ingest_batch(\n        client, args.url, section, args.search, args.limit, split_list(args.exclude), args.max_chars\n    )\npython\ndef summary_lines(dataset):\n    s = summarize(dataset)\n    skipped = \", \".join(f\"{reason} {count}\" for reason, count in s[\"skipped\"].items()) or \"none\"\n    return [\n        f\"Included {s['included']} pages as {s['chunks']} chunks\",\n        f\"Skipped: {skipped}\",\n        f\"Failed: {s['failed']}\",\n    ]\n\ndef show_search(index, query):\n    lines = [f'Test search: \"{query}\"']\n    for hit in index.search(query, 3):\n        lines.append(f\"  {hit['score']:>5}  {hit['url']}  [{' > '.join(hit['heading_path'])}]\")\n    return lines\npython\ndef diff_line(args, dataset):\n    diff = diff_manifests(read_jsonl(args.previous), dataset[\"pages\"])\n    return [\n        \"Changed since last run: \" + \", \".join(f\"{key} {len(urls)}\" for key, urls in diff.items())\n    ]\n\ndef score_line(index, path):\n    tests = [(t[\"question\"], t[\"url\"]) for t in json.loads(Path(path).read_text(encoding=\"utf-8\"))]\n    found = hit_rate(index, tests)\n    return [\n        f\"Retrieval: {found['hit']} of {found['asked']} questions found their page in the top 3\"\n    ]\npython\ndef extras(args, dataset):\n    \"\"\"The optional steps: what changed since last time, a test search, and a retrieval score.\"\"\"\n    index = Index(dataset[\"chunks\"]) if dataset[\"chunks\"] and (args.query or args.tests) else None\n    lines = diff_line(args, dataset) if args.previous else []\n    lines += show_search(index, args.query) if index and args.query else []\n    return lines + (score_line(index, args.tests) if index and args.tests else [])\n\ndef run(args, client, read):\n    dataset = ingest(args, client, read)\n    save_dataset(dataset, args.out)\n    print(\"\\n\".join(summary_lines(dataset) + extras(args, dataset)))\n    if not summarize(dataset)[\"included\"]:\n        raise Failure(\"no pages were ingested. Check the URL and --section.\", NO_PAGES)\n    return SOME_FAILED if summarize(dataset)[\"failed\"] else 0\npython\ndef main(argv=None, client=None, read=None):\n    args = build_parser().parse_args(argv)\n    try:\n        if args.limit < 1 or args.max_chars < 100:\n            raise Failure(\"--limit must be at least 1 and --max-chars at least 100.\", BAD_OPTIONS)\n        return run(args, client or make_client(), read)\n    except Failure as failure:\n        print(f\"error: {failure.message}\", file=sys.stderr)\n        return failure.code\n    except Exception as error:  # a Spidra error, a timeout or a failed crawl: say it in one line\n        failure = failure_from(error)\n        print(f\"error: {failure.message}\", file=sys.stderr)\n        return failure.code\n```\n\nSave 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.\n\nThe 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.\n\n## A docs dataset that stays current\n\nYou 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.\n\nHere is what Spidra gives you for that job:\n\n- **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.\n- **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.\n- **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.\n- **Respect for the site.** Map and Crawl can honor robots.txt, so a recurring ingestion stays polite.\n- **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.\n- **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.\n\nA 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.\n\n[Create a free account](https://app.spidra.io/), point `ingest_docs.py` at a documentation site your product depends on, and read the manifest. Our [Map then batch scrape](https://spidra.io/blog/map-website-batch-scrape-selected-pages) post covers the first half in more depth, the [batch scrape docs](https://docs.spidra.io/batch-scrape) list every option, and the [guides](https://docs.spidra.io/guides/overview) include a RAG walkthrough.", "url": "https://wpnews.pro/news/how-to-crawl-a-documentation-website-for-rag", "canonical_source": "https://spidra.io/blog/crawl-documentation-website-for-rag", "published_at": "2026-12-01 00:00:00+00:00", "updated_at": "2026-12-01 18:44:36.177862+00:00", "lang": "en", "topics": ["ai-crawlers", "ai-tools", "large-language-models"], "entities": ["Spidra", "FastAPI", "Python", "Spidra Map", "SPIDRA_API_KEY"], "also_reported_by": [], "takeaway": "Map a docs site before scraping and filter duplicate translated and versioned URLs — on the FastAPI docs, 3 of the first 5 'dependencies' matches were German, Spanish and French copies of one reference page — then chunk by heading without cutting code blocks.", "recommendation": {"advice": "Map the site first and drop translated and old-version URL duplicates before fetching; on the FastAPI docs, 3 of 5 top matches were foreign-language copies of one page.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/how-to-crawl-a-documentation-website-for-rag", "markdown": "https://wpnews.pro/news/how-to-crawl-a-documentation-website-for-rag.md", "text": "https://wpnews.pro/news/how-to-crawl-a-documentation-website-for-rag.txt", "jsonld": "https://wpnews.pro/news/how-to-crawl-a-documentation-website-for-rag.jsonld"}}