AI & ML

Turning Web Pages into Clean Markdown for RAG: What Breaks and How to Fix It

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

Turning Web Pages into Clean Markdown for RAG: What Breaks and How to Fix It

VP
Vasyl Popovych
Published in
Web·
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

Turning Web Pages into Clean Markdown for RAG: What Breaks and How to Fix It
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

Run Apple's MacBook Air page through trafilatura, a Python library that pulls the main text out of web pages, and you get 106 words back. The page has more than 7,000 words of visible text. If you build retrieval-augmented generation (RAG), that gap decides what your model can find.

The team at Apify, which makes one of the three tools compared below, turned 20 public web pages into Markdown three ways and measured what broke. The numbers in this article come from that test. SitePoint's guide on building a fetch layer for AI agents covers getting the page. This article picks up where it leaves off, at the line "extract_main_text is whatever readability or boilerplate-removal step you already use". Here's what breaks in that step and the Python to fix each problem.

Key Takeaways

  • Converting a whole page to Markdown keeps the menus, footers, and link lists. In the test it used 3.4 times the tokens of a main-content extractor.
  • The extractor in the test kept under 2% of the visible text on two product pages, and its recall setting didn't help.
  • Pages rendered with JavaScript can return an empty shell to a plain HTTP request. Check the visible text before you trust the output.
  • Check structure too. One extractor dropped every heading on a GitHub docs page and flattened Python code examples.
  • Remove blocks repeated across a site, then chunk by heading. In an extra test on four GitHub docs pages, blocks repeated across pages made up 43% of the tokens (1.3% on Python docs).

The Test: 20 Pages, Three Methods

The test used four pages each of five types: documentation (Python, MDN, FastAPI, GitHub), blog posts, news and Wikipedia articles, product pages (Apple, a GitHub repository, Allbirds, IKEA), and pages that render with JavaScript (crates.io, Bluesky, Mastodon, a Notion help page).

Each page went through three methods on November 5, 2026:

  1. Plain conversion: requests plus markdownify on the whole HTML.
  2. Main-content extraction: trafilatura 2.0.0 on the same HTML.
  3. A rendering crawler: Website Content Crawler from Apify, which loads the page in a headless browser before converting it.

Tokens were counted with tiktoken (the o200k_base encoding that GPT-4o uses), along with lines that look like boilerplate: cookie notices, "sign in", "subscribe", copyright lines.

  • Plain conversion: 210,158 tokens across the 20 pages, 3 pages under 100 words, 179 boilerplate lines, 152 Markdown table rows, 2 pages with no headings.
  • trafilatura: 62,236 tokens, 5 pages under 100 words, 8 boilerplate lines, 10 Markdown table rows, 8 pages with no headings.
  • Website Content Crawler: 106,332 tokens, 1 page under 100 words, 12 boilerplate lines, 86 Markdown table rows, 0 pages with no headings.

[IMAGE: Bar chart: total tokens for the same 20 pages: plain conversion 210,158, Website Content Crawler 106,332, trafilatura 62,236]

Total tokens after converting the same 20 pages. Test run on November 5, 2026.

No method won on every page. The rest of this article goes through the failures one at a time.

Problem 1: Most of the Page Isn't Content

The first thing most people write looks like this:

python

import requests
from markdownify import markdownify

HEADERS = {"User-Agent": "my-rag-bot/1.0 (+https://example.com/bot)", "Accept": "text/html"}

def naive_markdown(url):
    html = requests.get(url, headers=HEADERS, timeout=30).text
    return markdownify(html, heading_style="ATX")

It does work, and you get Markdown. The problem is that you get everything with it: menus, footers, cookie notices, and the article somewhere in the middle. On the Cloudflare blog post in the set, the plain conversion was 19,425 tokens. The extracted article was 4,541. Across 20 pages, the plain output had 5,444 links, 179 boilerplate lines, and 332 lines repeated within the same page. Every one of those ends up in an embedding, where a question like "how do I sign in" can pull up a navigation chunk instead of the real answer.

A main-content extractor scores each block of the page and keeps the ones that look like the body:

python

import trafilatura

def extract_markdown(html):
    return trafilatura.extract(
        html,
        output_format="markdown",
        include_tables=True,
        include_links=True,
        include_comments=False,
    )

On articles this works well. Across all 20 pages, boilerplate lines fell from 179 to 8, and total tokens fell by 70%. The trouble starts on pages that aren't articles.

Problem 2: The Extractor Throws Away Pages That Aren't Articles

Extractors like this are built around articles. Product pages, landing pages, and repository pages don't look like that, so the extractor keeps a fragment and drops the rest:

  • Apple MacBook Air: 7,158 visible words in the HTML. trafilatura kept 106, Website Content Crawler kept 1,513.
  • Allbirds product page: 15,298 visible words in the HTML. trafilatura kept 200, Website Content Crawler kept 1,244.
  • IKEA BILLY bookcase: 2,395 visible words in the HTML. trafilatura kept 412, Website Content Crawler kept 3,238.

Setting trafilatura's favor_recall=True made no real difference on any of the three.

The fix is to notice the problem per page. Compare what the extractor kept with how much text the page has:

python

from bs4 import BeautifulSoup

def visible_words(html):
    soup = BeautifulSoup(html, "lxml")
    for tag in soup(["script", "style", "noscript", "template"]):
        tag.decompose()
    return len(soup.get_text(" ").split())

def diagnose(html, markdown):
    page = visible_words(html)
    kept = len((markdown or "").split())
    if page < 200:
        return "needs_browser"          # the HTML is an empty app shell
    if kept < 0.15 * page:
        return "extractor_dropped_content"   # not an article: product, landing, listing page
    return "ok"

For pages flagged extractor_dropped_content, fall back to converting the page's main region with the obvious noise removed:

python

from bs4 import BeautifulSoup
from markdownify import markdownify

NOISE = ["nav", "header", "footer", "aside", "form", "script", "style",
         "noscript", "svg", "button", "iframe", "[role=dialog]", "[aria-hidden=true]"]

def main_region_markdown(html):
    soup = BeautifulSoup(html, "lxml")
    root = soup.select_one("main, [role=main], article") or soup.body
    for selector in NOISE:
        for tag in root.select(selector):
            tag.decompose()
    return markdownify(str(root), heading_style="ATX")

In the test set, diagnose sent Apple, Allbirds, and the Notion help page to the fallback, and marked the three JavaScript shells from Problem 3 as needs_browser. The fallback brought Apple from 106 words to 3,845, Allbirds from 200 to 921, and Notion from 45 to 195. It's a blunter tool than the extractor, so use it only as a fallback. The 15% threshold is a judgment call: IKEA kept 17% and passed, even though the crawler found far more text. Tune it on your own pages.

Problem 3: JavaScript Pages Come Back Empty

Three of the four JavaScript pages in the set build their content in the browser, so the HTML that requests gets is an app shell with almost no text (the Notion help page had enough text in its HTML to pass):

  • crates.io (serde): 4 visible words in the HTML. The plain conversion returned 16, Website Content Crawler 278.
  • Bluesky profile: 3 visible words in the HTML. The plain conversion returned 31, Website Content Crawler 135.
  • Mastodon profile: 4 visible words in the HTML. The plain conversion returned 26, Website Content Crawler 2,283.

The plain conversion has a few more words only because it keeps the page title and the "enable JavaScript" notice. No extractor can recover text that isn't in the HTML. The needs_browser branch of diagnose catches these, and they need a real browser. You can run Playwright yourself, or hand the URLs to a hosted crawler. The test used Website Content Crawler, a hosted crawler from Apify. It renders each page, removes navigation and cookie banners, and returns Markdown. The code below needs apify-client 3 or later (pip install "apify-client>=3"):

python

import os
from apify_client import ApifyClient

def render_with_crawler(urls):
    client = ApifyClient(os.environ["APIFY_TOKEN"])
    run = client.actor("apify/website-content-crawler").call(run_input={
        "startUrls": [{"url": u} for u in urls],
        "maxCrawlDepth": 0,               # only the URLs you pass in
        "crawlerType": "playwright:firefox",
        "respectRobotsTxtFile": True,
        "removeCookieWarnings": True,
    })
    items = client.dataset(run.default_dataset_id).iterate_items()
    return {item["url"]: item["markdown"] for item in items}

[IMAGE: Grouped bar chart of words kept per page by trafilatura and Website Content Crawler: Apple 106 vs 1,513, Allbirds 200 vs 1,244, IKEA 412 vs 3,238, crates.io 12 vs 278, Bluesky 26 vs 135, Mastodon 21 vs 2,283]

Words kept per page on the product and JavaScript pages.

Rendering does not mean you are done, though. When the function was rerun as a check, crates.io came back with 278 words again, but the Bluesky profile came back with 9 words instead of 135. Pages like that can load content in stages, so check the rendered output too. The crawler returns Markdown, not HTML, so a word count is enough: retry or wait longer if it's still thin. Website Content Crawler has a waitForSelector setting for this case.

If you'd rather run the browser yourself, Playwright does the rendering part. Install it with pip install playwright and playwright install chromium, then pass the rendered HTML through the same main_region_markdown fallback from Problem 2:

python

from playwright.sync_api import sync_playwright

def render_with_playwright(urls, settle_ms=2000):
    results = {}
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(user_agent=HEADERS["User-Agent"])
        for url in urls:
            page.goto(url, wait_until="networkidle", timeout=60_000)
            page.wait_for_timeout(settle_ms)  # let staged content load
            results[url] = main_region_markdown(page.content())
        browser.close()
    return results

On a test page that builds its content in JavaScript, a plain request returned only the "Loading…" placeholder, while this function returned both headings and their paragraphs. You get full control and no per-page fee, but you also run, scale and update the browsers yourself, and you still need your own handling for cookie banners and consent dialogs.

Problem 4: Headings, Code, and Tables Get Lost

Word counts tell you whether text survived. They don't tell you whether the structure did, and RAG depends on structure. Headings become chunk boundaries, code needs its indentation, and a table that turns into a run of numbers can't answer "what's the limit for X".

Between them, two pages in the set showed all three problems with trafilatura:

  • GitHub's REST API rate limits page had 19 headings in the HTML and 0 in the output.
  • Python's json docs had 17 table rows in the HTML and 0 in the output. Code examples lost their indentation: def default(self, obj): and the lines of its body came out at the same level, which isn't valid Python anymore.

Website Content Crawler kept 13 of the GitHub headings and all 17 table rows on the Python page. It isn't perfect either. On the Python page it kept 11 of 17 headings, and its code examples kept their indentation but came out as plain text, without code fences and with characters like [ and = escaped. On a short post by Simon Willison it kept 30 words where trafilatura kept 77.

So check structure on every page, whatever tool you use:

python

import re
from bs4 import BeautifulSoup

def count_code_blocks(markdown):
    fenced = markdown.count("```") // 2
    indented = len(re.findall(r"(?:^|\n\n)(?: {4}|\t)\S", markdown))
    return fenced + indented

def structure_report(html, markdown):
    soup = BeautifulSoup(html, "lxml")
    lines = markdown.splitlines()
    return {  # (in the HTML, in your Markdown)
        "headings": (len(soup.select("h2, h3")), sum(bool(re.match(r"#{2,3} ", l)) for l in lines)),
        "code_blocks": (len(soup.select("pre")), count_code_blocks(markdown)),
        "table_rows": (len(soup.select("table tr")), sum(l.lstrip().startswith("|") and not re.fullmatch(r"[\s|:-]+", l) for l in lines)),
    }

For the GitHub page and trafilatura, it returns "headings": (19, 0). Log pages where the second number is far below the first, and route them to a different method.

Problem 5: The Same Navigation on Every Page

Extractors judge each page on its own by default (trafilatura has an optional deduplicate setting), so they don't see that a block appears on every page of a site. When you index a whole docs site, the menu, breadcrumbs, and "Skip to content" links get embedded once per page. Look at the site as a whole instead:

python

import hashlib
import re
from collections import Counter

def _key(block):
    return hashlib.sha1(re.sub(r"\W+", " ", block.lower()).strip().encode()).hexdigest()

def drop_repeated_blocks(pages, min_pages=3):
    """pages: dict of url -> markdown from the same site.
    Removes blocks (paragraphs, list items) that appear on min_pages or more pages."""
    blocks = {url: [b for b in md.split("\n\n") if b.strip()] for url, md in pages.items()}
    seen = Counter(k for bs in blocks.values() for k in {_key(b) for b in bs})
    return {
        url: "\n\n".join(b for b in bs if seen[_key(b)] < min_pages)
        for url, bs in blocks.items()
    }

In an extra test outside the 20-page set, on four GitHub REST docs pages converted with plain markdownify, this removed 79 blocks from the first page alone ("Skip to main content", "Menu", "Collapse sidebar") and cut the four pages from 34,207 tokens to 19,606, a 43% drop. On four Python library docs pages it removed only 1.3%, because Python's navigation is small next to the content. Run it and measure; don't assume.

Set min_pages with care. On a small site, a real paragraph that appears on three pages (a shared warning, say) will be removed. Headings are blocks too, so a section title that repeats across pages, like "Parameters", goes as well. If you chunk by heading next, skip blocks that start with # when you count.

Problem 6: Chunks Without Context

The last step is splitting each page into chunks for embedding. Splitting every N tokens cuts sections in half and loses the heading that says what the text is about. Split on headings, keep the heading path with each chunk, and only split further when a section is too long:

python

import re
import tiktoken

ENC = tiktoken.get_encoding("o200k_base")
HEADING = re.compile(r"^(#{1,3})\s+(.*)")
LINK = re.compile(r"\[([^\]]+)\]\([^)]*\)")

def sections(markdown):
    path, buf, in_code = [], [], False
    for line in markdown.splitlines():
        in_code ^= line.startswith("```")
        m = None if in_code else HEADING.match(line)
        if m:
            yield " > ".join(path), "\n".join(buf).strip()
            path = path[: len(m.group(1)) - 1] + [LINK.sub(r"\1", m.group(2)).strip()]
            buf = []
        else:
            buf.append(line)
    yield " > ".join(path), "\n".join(buf).strip()

def chunk_markdown(markdown, source_url, max_tokens=400):
    chunks = []
    for section, text in sections(markdown):
        part = []
        for para in filter(None, text.split("\n\n")):
            if part and len(ENC.encode("\n\n".join(part + [para]))) > max_tokens:
                chunks.append({"url": source_url, "section": section, "text": "\n\n".join(part)})
                part = []
            part.append(para)
        if part:
            chunks.append({"url": source_url, "section": section, "text": "\n\n".join(part)})
    return chunks

This is where Problem 4 comes back. The trafilatura output for the GitHub page gave 8 chunks, none with a section path, because it had no headings. The crawler's output gave 15 chunks, each labeled like "Rate limits for the REST API > About primary rate limits > Primary rate limit for unauthenticated users". Store section and url as metadata, and put the section path at the top of the text you embed.

One limit: a single paragraph or code block longer than max_tokens stays whole. On the Python docs, one chunk was 1,137 tokens. Split those further if your embedding model needs it.

Putting It Together

A pipeline that holds up on mixed pages looks like this:

  1. Fetch the page (see the fetch-layer guide linked above).
  2. Extract the main content with trafilatura.
  3. Run diagnose. Render needs_browser pages in a browser; convert extractor_dropped_content pages with the main-region fallback.
  4. Run structure_report and route pages that lost headings, code, or tables to another method.
  5. Drop blocks repeated across the site.
  6. Chunk by heading, with the section path and URL as metadata.

The takeaway from this test: don't pick one converter for everything. trafilatura gave the leanest output overall. The rendering crawler was the only method that got the JavaScript pages, and it kept more of the docs structure than trafilatura, at the cost of a browser per page. The test didn't run trafilatura on rendered HTML, so part of that gap may come from rendering, not extraction, and some of trafilatura's lean output is content it dropped (Problem 2). The checks between the steps are what make either of them safe to use.

Wrapping Up

Every problem found in this test came from the conversion step: navigation embedded as content, product pages reduced to a paragraph, JavaScript pages indexed as empty, and docs without headings. Measure each page you convert, using word counts against the visible text and structure counts against the HTML, and send the failures down a different path. Start with the diagnose and structure_report functions above on a sample of your own pages. They run locally on HTML you already have and tell you which of these problems you have.

FAQs

Why convert to Markdown instead of plain text?

Markdown keeps headings, lists, tables, and code blocks, so your chunker can split on them and a large language model (LLM) can see the structure. Plain text loses that structure, and with it the chunk boundaries and section labels.

Keep them if your answers should cite or follow them. Drop them if they're mostly navigation. In the test, plain conversions had 5,444 links across 20 pages; after extraction, 909 were left.

Is it OK to collect pages for RAG?

Check each site's terms and robots.txt, identify your bot honestly, and keep request rates low. The fetch-layer guide linked above covers this in detail. Website Content Crawler has a setting to respect robots.txt, which was turned on for this test.

How big should chunks be?

There's no single right size. The examples here use 400 tokens as a limit and headings as the main boundary. Test a few sizes against real questions from your users and keep the one that retrieves the right section most often.

proton_pass_2026_11_footer
Source: Vasyl Popovych · www.sitepoint.com