← Back to blog

HTML vs Markdown for LLMs: What 7 Real Web Pages Actually Cost in Tokens

Every time your agent reads a web page, it pays for the whole page — not just the article. Cookie banners, navigation menus, inline SVG icons, analytics snippets, and 200 KB of JavaScript all get converted into tokens that your model has to wade through before it reaches the sentence it actually needed.

We wanted a real number instead of a vibe, so we ran seven very different pages through the Markdownify API and measured what came out the other side. The results ranged from a 74% reduction to a 99.6% reduction — and the page with the biggest HTML file was nowhere near the page with the most content.

Here's the data, what it means, and how to build a pipeline that doesn't burn context on boilerplate.

Why raw HTML is a token tax

A typical modern web page is mostly scaffolding. A news article might be 1,200 words wrapped in 400 KB of markup: a <head> full of meta tags, a framework bundle, hydration JSON, ad slots, a mega-menu, and a footer with forty links.

If you curl that page and paste it into a prompt, you're paying for all of it. Worse, the model has to find the content among the noise, which degrades answer quality — the classic "lost in the middle" problem, except the middle is a cookie consent string.

Cleaned markdown fixes three things at once:

The experiment

For each URL we measured two things:

  1. The decompressed size of the raw HTML (curl -sL --compressed ... | wc -c).
  2. The markdown returned by GET /v1/markdownify, including its word_count and char_count fields.

Token counts below are estimates at roughly 4 characters per token, which is close enough for English prose and directionally correct for code. This isn't a tokenizer benchmark — it's a comparison of input shapes, which is the decision you're actually making.

# 1. How big is the raw page?
curl -sL --compressed "https://stripe.com/payments" | wc -c

# 2. What does the cleaned version look like?
curl -s "https://fetchapi.tech/v1/markdownify?url=https://stripe.com/payments" -o page.json

python3 -c "import json; d=json.load(open('page.json')); print(d['word_count'], 'words /', d['char_count'], 'chars')"

The results

Page Raw HTML Markdown chars Words Size reduction
github.com/trending 593 KB 2,276 327 99.6%
stripe.com/payments 1,183 KB 7,480 1,104 99.4%
developer.mozilla.org/.../Fetch_API 150 KB 3,302 387 97.8%
python.org 51 KB 2,581 143 95.0%
en.wikipedia.org/wiki/Retrieval-augmented_generation 247 KB 19,602 2,036 92.2%
example.com 0.6 KB 156 25 74.6%
docs.python.org/3/library/asyncio-task.html 173 KB 45,871 5,847 74.1%

Two pages failed extraction entirely — more on those below, because the failure mode is instructive.

Three things the numbers reveal

1. The savings are enormous, but wildly uneven

The median page in this set shed about 95% of its bytes. In token terms, Stripe's payments page went from roughly 300,000 tokens of raw HTML to about 1,900 tokens of markdown. That's the difference between "this doesn't fit in my context window" and "this fits alongside thirty other pages."

But look at the bottom of the table. Documentation pages only compressed by about 74%, because their HTML is already lean and their content is genuinely long. A 5,800-word asyncio tutorial should be big. The lesson isn't "markdown is always 95% smaller" — it's "markdown removes the part that was never content."

2. HTML size tells you nothing about content size

This is the most useful finding for pipeline design:

The GitHub page is three times larger and has eighteen times less to say. Its HTML is almost entirely React payload, inline styles, and SVG.

So never budget by page weight. Budget by word_count from the API response, which is free and returned on every call:

{
  "url": "https://github.com/trending",
  "word_count": 327,
  "char_count": 2276
}

If word_count is under ~50 on a page you expected to be an article, treat it as an extraction failure, not a short article. That single check catches most silent breakage.

3. Markdown keeps the structure your prompts depend on

The point isn't just fewer characters — it's that the characters left are the right ones. Headings become ##, lists stay lists, code blocks stay fenced, and links keep their text and href. When you chunk a document for RAG, those headings are what let you split on section boundaries instead of arbitrary character counts.

If you're building retrieval on top of this, our guide to building a RAG pipeline with the YouTube Transcript API covers the chunking and embedding side in detail.

Where extraction fails — and the fallback ladder

Two of our nine test pages didn't produce content:

The fix isn't a bigger model. It's a routing layer that picks the cheapest tool that can actually answer the question:

URL type Tool Why
Article, docs, blog post /v1/markdownify Full text as clean markdown
Unknown link in a list /v1/ogsnap Title, description, image in ~200 tokens
YouTube URL /v1/transcript Captions with timestamps, no audio processing
YouTube metadata only /v1/info Title, channel, duration, view count, has_transcript
JS-only app, no SSR Headless browser Last resort — slow and expensive

A link-preview-first strategy is worth emphasizing. When a user pastes twenty URLs, call OGSnap on all of them first. At roughly 200 tokens each, twenty previews cost less than one full article, and the model can decide which two pages deserve the expensive read.

curl -s "https://fetchapi.tech/v1/ogsnap?url=https://github.com" | python3 -m json.tool
{
  "url": "https://github.com",
  "title": "GitHub · Change is constant. GitHub keeps you ahead. · GitHub",
  "description": "Join the world's most widely adopted, AI-powered developer platform...",
  "image": "https://images.ctfassets.net/.../GH-Homepage-Universe-img.png",
  "site_name": "GitHub",
  "type": "object"
}

For video links, /v1/info is the cheapest possible pre-flight check because it tells you whether captions exist before you request them:

curl -s "https://fetchapi.tech/v1/info?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ"
{
  "video_id": "dQw4w9WgXcQ",
  "title": "Rick Astley - Never Gonna Give You Up (Official Video) (4K Remaster)",
  "duration_seconds": 213,
  "has_transcript": true
}

A production pattern: fetch once, cache, budget

The pipeline that survives contact with real traffic looks like this:

  1. Normalize the URL (strip tracking params, resolve redirects).
  2. Look up a cache keyed by URL.
  3. On a miss, call the right endpoint with a timeout and one retry.
  4. Validate the payload — non-empty content, word_count above a floor, JSON that actually parses.
  5. Store markdown plus a content hash and timestamp.
  6. Send only what fits the budget, splitting on headings when it doesn't.
import hashlib
import httpx

API = "https://fetchapi.tech/v1"

def fetch_markdown(url: str, timeout: float = 30.0) -> dict:
    for attempt in range(2):
        try:
            r = httpx.get(f"{API}/markdownify", params={"url": url}, timeout=timeout)
            if r.status_code == 429:
                raise RuntimeError("rate limited")
            data = r.json()
            if not data.get("content") or data.get("word_count", 0) < 20:
                return {"url": url, "error": "no_content"}
            data["hash"] = hashlib.sha256(data["content"].encode()).hexdigest()[:16]
            return data
        except (httpx.TimeoutException, httpx.TransportError, ValueError):
            if attempt == 1:
                return {"url": url, "error": "fetch_failed"}
    return {"url": url, "error": "unreachable"}

def chunk_by_headings(markdown: str, max_chars: int = 12_000) -> list[str]:
    """Split on H2s, then hard-split any section that is still too long."""
    sections, current = [], []
    for line in markdown.splitlines(keepends=True):
        if line.startswith("## ") and sum(map(len, current)) > max_chars // 2:
            sections.append("".join(current))
            current = []
        current.append(line)
    sections.append("".join(current))

    chunks = []
    for section in sections:
        while len(section) > max_chars:
            cut = section.rfind("\n", 0, max_chars)
            cut = cut if cut > 0 else max_chars
            chunks.append(section[:cut])
            section = section[cut:]
        if section.strip():
            chunks.append(section)
    return chunks

The content hash matters more than it looks. It gives you a cheap way to answer "did this page actually change?" — and when DiffCheck lands, you'll already have the snapshots it needs to compare against.

The budget math

Say you ingest 1,000 pages a month and the average page is like Wikipedia's RAG article: 247 KB of HTML, 19.6 KB of markdown.

At cheap-model input pricing the dollar difference is modest. The operational difference is not. At 4,900 tokens you can fit twenty-six documents into a 128K context window instead of two. Retrieval gets better because you can afford more candidates. Latency drops because you're sending less. And your logs become readable, which means you can debug why the agent answered wrong.

That's the real argument for cleaning before prompting: not the invoice, but the headroom.

A five-item pre-flight checklist

Before you ship any page-reading feature, confirm each of these:

Try it on your own worst page

Pick the heaviest page your product touches — a pricing table, a docs index, a CMS article — and run it through the API:

curl -s "https://fetchapi.tech/v1/markdownify?url=YOUR_URL_HERE" | python3 -m json.tool | head -40

Compare word_count to what the page actually says. If the gap surprises you, that's the boilerplate you've been paying for on every single request. The free tier needs no API key, so you can measure your own corpus before you commit to an architecture — and the docs cover every parameter, including plain-text output for pipelines that don't need JSON.