Most RAG tutorials start with "crawl the docs site". On a real docs site that means thousands of pages: changelogs, translated copies, old versions, API pages you will never query. You pay to fetch them, embed them and store them, and then your retriever has more noise to wade through.
A cheaper pattern is map, rank, then scrape:
- Get the list of URLs on the site, with their titles (no page content yet).
- Keep only the URLs that are relevant to the questions your app answers.
- Fetch just those pages as Markdown and split them on headings.
This post builds that pipeline in about 80 lines of Python. It uses plain requests against a web data API for steps 1 and 3, so you can swap in your own crawler later if you prefer.
Setup
pip install requests
export SCREENSHOTRENDER_API_KEY=sr-...
I'm using ScreenshotRender's /map and /scrape endpoints because /map can order URLs by relevance to a search string, which does step 2 for free. New accounts get 100 free credits, which is plenty for this tutorial. Any service (or your own Playwright script) that returns a URL list and Markdown will slot in.
import os, re, requests
API = "https://www.screenshotrender.com/api/v1"
HEADERS = {
"Authorization": f"Bearer {os.environ['SCREENSHOTRENDER_API_KEY']}",
"Content-Type": "application/json",
}
def post(path, payload):
r = requests.post(f"{API}/{path}", json=payload, headers=HEADERS, timeout=120)
r.raise_for_status()
body = r.json()
if not body.get("success"):
raise RuntimeError(body)
return body["data"]
Step 1 and 2: map the site, ranked by your topic
/map takes a url, an optional search string and a limit. With search, the links come back ordered by relevance to it, each with a url and title.
def relevant_urls(site, topic, limit=40):
data = post("map", {"url": site, "search": topic, "limit": limit})
links = data["links"]
# Drop obvious noise: other languages, old versions, release notes.
skip = re.compile(r"/(ja|zh|ko|fr|de|es)/|/v\d+(\.\d+)*/|changelog|release-notes", re.I)
return [l for l in links if not skip.search(l["url"])]
urls = relevant_urls("https://docs.python.org/3/", "asyncio tasks and event loop", limit=30)
for l in urls[:10]:
print(l["url"], "|", l.get("title"))
Print the list before you scrape anything. This is the cheapest moment to notice that your filter is too loose. If the top results look wrong, change the search phrase rather than raising the limit.
Step 3: scrape the winners as Markdown
/scrape returns Markdown by default, rendered in a real browser, so JavaScript-heavy docs sites work too. The scrape docs list the extra page options if your target needs them.
def fetch_markdown(url):
data = post("scrape", {"url": url, "formats": ["markdown"]})
return data.get("markdown") or ""
Chunk on headings, not on character counts
Docs pages already have structure. Splitting on ## and ### keeps each chunk about one thing, and you can carry the heading path along as metadata, which helps both retrieval and citations.
def chunk_markdown(md, url, max_chars=2500):
chunks, path = [], []
for block in re.split(r"(?m)^(?=#{1,3} )", md):
if not block.strip():
continue
m = re.match(r"(#{1,3}) (.+)", block)
if m:
level = len(m.group(1))
path = path[: level - 1] + [m.group(2).strip()]
# Hard-split very long sections so no chunk blows the embedder's limit.
for i in range(0, len(block), max_chars):
chunks.append({
"url": url,
"section": " > ".join(path),
"text": block[i : i + max_chars].strip(),
})
return chunks
Put it together
def ingest(site, topic, top_n=8):
all_chunks = []
for link in relevant_urls(site, topic)[:top_n]:
try:
md = fetch_markdown(link["url"])
except requests.HTTPError as e:
print("skip", link["url"], e)
continue
all_chunks += chunk_markdown(md, link["url"])
return all_chunks
chunks = ingest("https://docs.python.org/3/", "asyncio tasks and event loop")
print(len(chunks), "chunks")
print(chunks[0]["section"], "\n", chunks[0]["text"][:300])
From here, hand chunks to whatever you already use: sentence-transformers plus FAISS, pgvector, Chroma, or a hosted vector DB. Store url and section as metadata so the model can cite where an answer came from.
Why this beats a blind crawl
- Cost scales with your questions, not the site. Eight pages instead of three thousand.
- Better retrieval. Fewer irrelevant chunks means fewer near-miss matches that crowd out the right one.
-
Easy refresh. Re-run
ingestnightly for the same topics; the map call is cheap, and you only re-scrape what you keep.
When you do need the whole site (for example to build a search index), a crawl endpoint or Scrapy is still the right tool. For "answer questions about X from these docs", map-rank-scrape is usually enough.
If you want to see what the Markdown looks like for a page before writing any code, paste a URL into the free HTML to Markdown tool. I've also written more about feeding web pages to LLMs if you want the background on why Markdown beats raw HTML in prompts.
Top comments (0)