How to crawl a documentation website for RAG 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. 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 : python 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 python 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 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: 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 https://spidra.io/docs/ \n Sign in https://spidra.io/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" python 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" python 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 "" python def segments path : """The lowercase parts of a URL path, without the empty ones.""" return s.lower for s in path.split "/" if s python 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 "" python 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 python 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 = "" python 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, python 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 python 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 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: 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 "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: python 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 python 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" python 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 python 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, python 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 python 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: python 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 python 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 }" python 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 python 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 python 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 https://spidra.io/docs/pagination ' is chrome too, though it differs on every page.""" return bool PAGER.match line and LINK ONLY.match line python 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 python 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 python 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 python 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 python 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 https://spidra.io/docs/ Sign in https://spidra.io/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: python 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 python 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 python 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 python 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 python 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 python 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 python 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, } python 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: python 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 python 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 python 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} python 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 , } python def failed row page : return { "url": page.url, "title": page.title, "status": "failed", "reason": "fetch failed", "error": page.error, } python 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 python 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} python 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" , } python 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, } python 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} python 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" python 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 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: 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 python 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 python 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: python 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 python 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 python 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" python 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" python 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 python 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 python 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" python 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 python 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 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.