{"slug": "build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that", "title": "Build a Docs-to-RAG Ingester in Python: Map a Site, Scrape Only the Pages That Matter", "summary": "A developer published an approximately 80-line Python pipeline that maps a documentation site, ranks URLs by relevance to a search phrase, and scrapes only the top matches into Markdown before chunking them by heading structure for RAG ingestion. The approach uses ScreenshotRender's /map and /scrape endpoints via plain requests, filters out translated, versioned and changelog pages, and hard-splits long sections to stay under embedder limits.", "body_md": "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.\n\nA cheaper pattern is **map, rank, then scrape**:\n\nThis 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.\n\n```\npip install requests\nexport SCREENSHOTRENDER_API_KEY=sr-...\n```\n\nI'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.\n\n``` python\nimport os, re, requests\n\nAPI = \"https://www.screenshotrender.com/api/v1\"\nHEADERS = {\n    \"Authorization\": f\"Bearer {os.environ['SCREENSHOTRENDER_API_KEY']}\",\n    \"Content-Type\": \"application/json\",\n}\n\ndef post(path, payload):\n    r = requests.post(f\"{API}/{path}\", json=payload, headers=HEADERS, timeout=120)\n    r.raise_for_status()\n    body = r.json()\n    if not body.get(\"success\"):\n        raise RuntimeError(body)\n    return body[\"data\"]\n```\n\n`/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`.\n\n``` python\ndef relevant_urls(site, topic, limit=40):\n    data = post(\"map\", {\"url\": site, \"search\": topic, \"limit\": limit})\n    links = data[\"links\"]\n    # Drop obvious noise: other languages, old versions, release notes.\n    skip = re.compile(r\"/(ja|zh|ko|fr|de|es)/|/v\\d+(\\.\\d+)*/|changelog|release-notes\", re.I)\n    return [l for l in links if not skip.search(l[\"url\"])]\n\nurls = relevant_urls(\"https://docs.python.org/3/\", \"asyncio tasks and event loop\", limit=30)\nfor l in urls[:10]:\n    print(l[\"url\"], \"|\", l.get(\"title\"))\n```\n\nPrint 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.\n\n`/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.\n\n``` python\ndef fetch_markdown(url):\n    data = post(\"scrape\", {\"url\": url, \"formats\": [\"markdown\"]})\n    return data.get(\"markdown\") or \"\"\n```\n\nDocs 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.\n\n``` python\ndef chunk_markdown(md, url, max_chars=2500):\n    chunks, path = [], []\n    for block in re.split(r\"(?m)^(?=#{1,3} )\", md):\n        if not block.strip():\n            continue\n        m = re.match(r\"(#{1,3}) (.+)\", block)\n        if m:\n            level = len(m.group(1))\n            path = path[: level - 1] + [m.group(2).strip()]\n        # Hard-split very long sections so no chunk blows the embedder's limit.\n        for i in range(0, len(block), max_chars):\n            chunks.append({\n                \"url\": url,\n                \"section\": \" > \".join(path),\n                \"text\": block[i : i + max_chars].strip(),\n            })\n    return chunks\npython\ndef ingest(site, topic, top_n=8):\n    all_chunks = []\n    for link in relevant_urls(site, topic)[:top_n]:\n        try:\n            md = fetch_markdown(link[\"url\"])\n        except requests.HTTPError as e:\n            print(\"skip\", link[\"url\"], e)\n            continue\n        all_chunks += chunk_markdown(md, link[\"url\"])\n    return all_chunks\n\nchunks = ingest(\"https://docs.python.org/3/\", \"asyncio tasks and event loop\")\nprint(len(chunks), \"chunks\")\nprint(chunks[0][\"section\"], \"\\n\", chunks[0][\"text\"][:300])\n```\n\nFrom 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.\n\n`ingest` nightly for the same topics; the map call is cheap, and you only re-scrape what you keep.\nWhen 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.\n\nIf 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.", "url": "https://wpnews.pro/news/build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that", "canonical_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_at": "2026-12-06 03:35:11+00:00", "updated_at": "2026-12-06 03:44:24.687262+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "large-language-models"], "entities": ["ScreenshotRender", "Python", "requests"], "also_reported_by": [], "takeaway": "Map and rank candidate URLs by relevance to a search phrase before scraping, then chunk docs on ## and ### headings and carry the heading path as metadata, so you embed only the pages you will query.", "recommendation": {"advice": "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.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that", "markdown": "https://wpnews.pro/news/build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that.md", "text": "https://wpnews.pro/news/build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that.txt", "jsonld": "https://wpnews.pro/news/build-a-docs-to-rag-ingester-in-python-map-a-site-scrape-only-the-pages-that.jsonld"}}