Most RAG tutorials skip straight from “get the data” to “embed it.” The result is a pipeline that technically works but retrieves irrelevant chunks, because the input was never cleaned in the first place.
Raw HTML is the usual culprit. Navigation menus, cookie banners, inline styles, and script blocks all get embedded alongside the actual content. Your similarity searches return noise, and your LLM generates answers grounded in footer links instead of the article body.
This guide covers the four steps between “I have a URL” and “I have clean, chunk-ready input.” No full pipeline tutorial. No tool roundup. Just the content preparation step, done properly.
Why Content Preparation is the Step That Makes or Breaks RAG
A typical documentation page is 8,000+ tokens as raw HTML. The same content, extracted and converted to markdown, runs about 1,200 tokens. That is not just a cost saving. It is a quality difference.
Every token in your embedding carries weight. When 85% of those tokens are navigation markup, your embedding represents “website with sidebar” more than it represents the actual topic of the page. Similarity search then returns results that are similar in structure (other pages with similar boilerplate) rather than similar in meaning.
Clean your content before it enters the pipeline. The rest of this guide shows you how.
What “Clean” Looks Like (Before and After)
Here is what a vector store sees when you skip content preparation:
<nav class="site-nav">
<ul><li><a href="/">Home</a></li><li><a href="/docs">Docs</a></li></ul>
</nav>
<div class="cookie-banner">We use cookies...</div>
<article>
<h2>Authentication</h2>
<p>All API requests require a Bearer token in the Authorization header.</p>
<pre><code>curl -H "Authorization: Bearer sk-..." https://api.example.com/data</code></pre>
</article>
<footer>© 2026 Example Inc. <a href="/privacy">Privacy</a></footer>
<script>analytics.track('page_view');</script>
And here is what it should see:
## Authentication
All API requests require a Bearer token in the Authorization header.
curl -H "Authorization: Bearer sk-..." https://api.example.com/data
The nav, cookie banner, footer, and analytics script are gone. What remains is the content and its structure: one heading, one paragraph, one code block. That is what you want in your vector store.
What got stripped: nav, footer, inline styles, script blocks, cookie consent, tracking pixels.
What got preserved: headings, paragraphs, code blocks, lists, links, emphasis. The semantic structure that tells your chunker where one topic ends and another begins.
Step 1: Extract the Content, Not the Page
Scraping a page’s full HTML is not the same as extracting its readable content. A full DOM scrape gives you everything: menus, sidebars, modals, scripts. A content extraction tool gives you the article body.
The standard approach is Readability-style extraction. Mozilla’s Readability algorithm (the same engine behind Firefox Reader View) scores DOM nodes by how likely they are to be content vs. boilerplate, then returns only the high-scoring subtree.
Python: Trafilatura or newspaper3k both handle extraction well. Trafilatura is the more actively maintained option and handles a wider range of page layouts.
JavaScript: Mozilla’s Readability.js is the reference implementation. Pair it with a DOM parser like jsdom or linkedom for server-side use.
One-off pages: CopyMarkdown handles extraction and conversion in a single step. Useful when you are building a knowledge base from a handful of specific pages rather than crawling an entire site.
For pipelines processing hundreds or thousands of URLs, automate extraction as the first stage. Never skip it.
Step 2: Convert to Markdown
Once you have clean HTML (the article body, not the full page), convert it to markdown. Markdown is the ideal intermediate format for RAG because of how its structure maps to chunking.
Headings become chunk boundaries. An H2 in markdown is an obvious place to split. Lists stay structured. Links preserve source attribution. Code blocks remain fenced and parseable.
Tools for this step:
- Turndown (JavaScript): The most popular HTML-to-markdown library. Handles tables, code blocks, and nested lists well.
- markdownify (Python): Lightweight, good defaults. Works well with Trafilatura output.
- Pandoc (CLI): Handles complex documents with footnotes, nested tables, and non-standard formatting. Overkill for simple pages.
Watch for these conversion issues:
- Relative URLs that need resolving to absolute (
/docs/authshould becomehttps://example.com/docs/auth) - HTML tables that collapse into unreadable single-line markdown
- Image references that become dead links if you are not hosting the images
Choosing between markdown and the alternatives? See the side-by-side comparison of markdown, DOCX, and PDF for AI workflows for token economics and structural fidelity across all three.
Step 3: Chunk Along the Structure
With clean markdown in hand, split it into chunks sized for your embedding model. This is where markdown’s structure pays off.
Heading-based chunking splits on H1, H2, and H3 boundaries. Each chunk gets the heading as context, keeping semantically related paragraphs together. In LangChain, the MarkdownHeaderTextSplitter does exactly this. In LlamaIndex, the MarkdownNodeParser is the equivalent.
Recursive character splitting is the fallback for content without clear heading structure. It tries paragraph breaks first, then sentence breaks, then character limits. Use this for pages that are mostly prose without subheadings.
Practical sizing: Most embedding models (OpenAI text-embedding-3-small, Cohere embed-v4, open-source alternatives like bge-large) perform best with chunks of 200 to 500 tokens. Larger chunks dilute the embedding. Smaller chunks lose context.
Attach metadata to every chunk. At minimum:
- Source URL for citations in generated answers
- Heading path (e.g., “Authentication > Bearer Tokens”) for debugging retrieval issues
- Timestamp for knowing when to re-embed
Step 4: Validate Before You Embed
Embedding is the expensive step. Spot-check before you commit.
Pull 10 random chunks and read them. Are they coherent on their own? Does each chunk contain one clear topic? If a chunk starts mid-sentence or contains a cookie banner fragment that slipped through extraction, your pipeline has a leak.
Check for duplicates. If you are ingesting multiple pages from the same site, shared boilerplate (headers, “about the author” sections, related post lists) can survive extraction and produce near-identical chunks. Hash each chunk’s content (SHA-256 is fine) and deduplicate before embedding.
Plan for refresh. Web content changes. Documentation gets updated. Blog posts get edited. Store content hashes alongside your embeddings so you can compare on the next crawl and only re-embed chunks that actually changed. This cuts ongoing embedding costs by 90%+ for stable knowledge bases.
Common Mistakes That Tank Retrieval Quality
Embedding raw HTML. This is the single most common mistake in production RAG systems. If your pipeline goes from URL to embedding without a content extraction step, every query competes with navigation markup for attention in the vector space.
Chunks that are too large. A 2,000-token chunk embeds into the same single vector as a 200-token chunk. The larger chunk’s embedding is a blurry average of everything in it. Smaller, focused chunks produce sharper embeddings and better retrieval.
Chunks that are too small. A single sentence stripped of its surrounding context is often ambiguous. “It supports OAuth2” means nothing without knowing what “it” refers to. Keep enough context in each chunk for it to stand alone.
Forgetting metadata. When your LLM cites a source in its answer, it needs the URL. When a user disputes a generated answer, you need to trace it back to the chunk that caused it. Without metadata, your pipeline is a black box.
Never refreshing. You built the index once. The source pages changed six months ago. Your users are now getting answers grounded in outdated information. Schedule re-crawls.
What to Read Next
This guide covered the content preparation layer. For a broader look at what wastes tokens and how to cut them across any LLM workflow, read How to Use Fewer Tokens and Get Better LLM Results.
If you want to make your own site’s content easy for AI agents to find and consume, llm.txt is the emerging standard for that.
If you want a fast way to handle Steps 1 and 2 for any URL, CopyMarkdown converts web pages to clean markdown, whether you are building a knowledge base or preparing a single page for a prompt.