# Build a Docs-to-RAG Ingester in Python: Map a Site, Scrape Only the Pages That Matter

> Source: <https://dev.to/robert_screenshotrender/build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that-matter-4d4i>
> Published: 2026-12-06 03:35:11+00:00

**Recommendation:** Print the ranked URL list before scraping and tighten the search phrase rather than raising the limit; then chunk on heading boundaries and hard-split sections at 2,500 characters.
More in the playbook "Retrieval and RAG": <https://wpnews.pro/playbooks/rag-retrieval>

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**:

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.

```
pip install requests
export SCREENSHOTRENDER_API_KEY=sr-...
```

I'm using [ScreenshotRender](https://www.screenshotrender.com)'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.

``` python
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"]
```

`/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`.

``` python
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.

`/scrape` returns Markdown by default, rendered in a real browser, so JavaScript-heavy docs sites work too. The [scrape docs](https://docs.screenshotrender.com/features/scrape) list the extra page options if your target needs them.

``` python
def fetch_markdown(url):
    data = post("scrape", {"url": url, "formats": ["markdown"]})
    return data.get("markdown") or ""
```

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.

``` python
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
python
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.

`ingest` nightly 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](https://www.screenshotrender.com/tools/html-to-markdown). I've also written more about [feeding web pages to LLMs](https://www.screenshotrender.com/blog/llm-web-scraping) if you want the background on why Markdown beats raw HTML in prompts.
