Your Scraped Markdown Is Full of Nav Junk: Strip It
Markdown output arrives stuffed with menus and footers. Trace why boilerplate leaks in, then strip nav junk before it reaches your parser or LLM.
On this page
The Boilerplate Problem
Your pipeline emits markdown. You point an LLM at it, or feed it to a diff tool, or store it for search. Then you look at an actual document and find 40 lines of menu links at the top, a breadcrumb trail rendered as > Home > Electronics > ..., a newsletter signup form mangled into a paragraph, and a footer with eighteen social-media links. The actual article starts on line 62.
This is the default behavior of every HTML-to-markdown converter, and it poisons everything downstream: token budgets, embeddings, change detection, and any model you feed the output to. The good news is that the fix is mechanical. The bad news is that most people reach for regex first, at the end of the pipeline, where it does the most damage. Work through this in order and you will get clean markdown without losing real content.
Why HTML-to-Markdown Converters Turn Your Nav Bar Into a Bullet List
Markdown converters are DOM walkers. markdownify, html2text, pandoc — none of them “understand” a page. They visit every text node in the document, in document order, and emit markdown for whatever they find. A <nav> element containing twenty <a> tags is, from the converter’s point of view, a list of twenty links. So that is exactly what you get.
Here is a stripped-down example.com page:
<!DOCTYPE html>
<html>
<body>
<nav>
<a href="/">Home</a>
<a href="/products">Products</a>
<a href="/pricing">Pricing</a>
<a href="/docs">Docs</a>
<a href="/blog">Blog</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
<a href="/careers">Careers</a>
<a href="/legal">Legal</a>
<a href="/status">Status</a>
</nav>
<article>
<h1>Example Product</h1>
<p>The widget handles 400 requests per second with a 12ms median latency.</p>
<p>It ships with a Python client and a webhook mode.</p>
</article>
<footer>
<p>© Example Corp. Follow us:</p>
<a href="/twitter">Twitter</a> <a href="/github">GitHub</a>
</footer>
</body>
</html>
And here is what markdownify produces from it, unmodified:
from markdownify import markdownify as md
print(md(html))
[Home](/) [Products](/products) [Pricing](/pricing) [Docs](/docs)
[Blog](/blog) [About](/about) [Contact](/contact)
[Careers](/careers) [Legal](/legal) [Status](/status)
# Example Product
The widget handles 400 requests per second with a 12ms median latency.
It ships with a Python client and a webhook mode.
© Example Corp. Follow us:
[Twitter](/twitter) [GitHub](/github)
Ten nav links. A footer. Two sentences of actual content. On a real page the ratio is worse — a store.example.com product page carries a mega-menu, filter sidebar, related-items carousel, and a footer with sitemap links, and the product description is maybe 15 percent of the rendered text.
The root cause is simple: the converter has no concept of “main content.” It cannot, because HTML does not require one. <nav>, <footer>, and <aside> are hints the page author may or may not have used, and the converter ignores even those. Everything you want must come from you.
Measure the Damage First: A Token Audit of One Uncleaned Conversion
Before you fix anything, get a number. If you cannot say “this page converts to 9,000 tokens and 6,000 of them are boilerplate,” you are guessing, and you will keep guessing after the fix too.
Here is a small audit script. It fetches a page, converts it raw, converts it cleaned, and prints the delta:
import requests, tiktoken
from bs4 import BeautifulSoup
from markdownify import markdownify as md
enc = tiktoken.encoding_for_model("gpt-4o-mini")
def audit(markdown_text, label):
chars = len(markdown_text)
lines = len(markdown_text.splitlines())
tokens = len(enc.encode(markdown_text))
print(f"{label:12} chars={chars:>7,} lines={lines:>5} tokens={tokens:>6}")
return tokens
API = "https://api.finedata.ai/scrape"
HEADERS = {"Authorization": "Bearer fd_your_api_key"}
payload = {
"url": "https://store.example.com/products/widget-pro",
"formats": ["rawHtml"],
}
html = requests.post(API, json=payload, headers=HEADERS).json()["data"]["rawHtml"]
raw_md = md(html)
soup = BeautifulSoup(html, "html.parser")
for tag in soup.select("nav, header, footer, aside, [role=navigation], [aria-hidden=true]"):
tag.decompose()
clean_md = md(str(soup))
raw_tok = audit(raw_md, "raw")
clean_tok = audit(clean_md, "cleaned")
print(f"boilerplate share of raw: {(raw_tok - clean_tok) / raw_tok:.1%}")
On a typical store.example.com product page fixture, the output looks like this:
raw chars= 38,412 lines= 611 tokens= 9,847
cleaned chars= 6,205 lines= 84 tokens= 1,502
boilerplate share of raw: 84.7%
| Metric | Raw conversion | Cleaned conversion | Boilerplate |
|---|---|---|---|
| Chars | 38,412 | 6,205 | 83.9% |
| Lines | 611 | 84 | — |
| Tokens | 9,847 | 1,502 | 84.7% |
Eighty-five percent of the tokens you were about to pay for — in embedding cost, in context window, in storage — are menu. That number is your baseline. Any cleanup you build has to beat it without touching the remaining 15 percent, and section eight covers how to verify that second part.
One honest caveat: the “cleaned” figure here is from naive tag pruning, which sometimes eats real content (a product spec table wrapped in an <aside>, for example). Never trust a single cleanup pass. That is why the validation step at the end is not optional.
Prune the DOM Before Conversion: Delete nav, header, footer, and aside Nodes
The primary fix. Do not clean the markdown — clean the DOM, then convert. The converter can only emit what is in the tree, so remove the junk from the tree.
from bs4 import BeautifulSoup
BOILERPLATE_SELECTORS = [
"nav",
"header",
"footer",
"aside",
"[role=navigation]",
"[role=banner]",
"[role=contentinfo]",
"[aria-hidden=true]",
"form", # search boxes, newsletter signups
"noscript",
]
def prune_dom(html: str) -> str:
soup = BeautifulSoup(html, "html.parser")
for selector in BOILERPLATE_SELECTORS:
for node in soup.select(selector):
node.decompose() # decompose(), not extract(): frees memory too
return str(soup)
Two details matter here.
First, decompose() destroys the node and its subtree. extract() also removes it but keeps it in memory as a detached tree — fine for one page, a slow leak when you process a hundred thousand. Use decompose().
Second, [aria-hidden=true] is the most underrated selector in the list. Icon fonts, decorative SVGs, screen-reader-only helper text, and a surprising amount of injected UI markup carry aria-hidden="true". None of it is content. It all converts to stray characters and orphan fragments.
The order is also worth thinking about: prune before conversion, not after, because the DOM still has structure that identifies the junk. Once it is markdown, a footer link list and a legitimate “related reading” list are indistinguishable — both are just lines of links.
Target the Content Container Instead of the Whole Page
Pruning is a blacklist strategy. The inverse is a whitelist: instead of deleting junk, select of the one node that holds the content and convert only that. On pages with decent semantics, this is more reliable, because it cannot miss a junk element type you forgot to blacklist.
CONTAINER_FALLBACKS = [
"main article",
"article",
"main",
"[itemprop=articleBody]",
'[role=main]',
"body",
]
def extract_container(html: str) -> str:
soup = BeautifulSoup(html, "html.parser")
for selector in CONTAINER_FALLBACKS:
node = soup.select_one(selector)
if node and len(node.get_text(strip=True)) > 200: # sanity floor
return str(node)
return str(soup.body or soup)
The sanity floor matters. Plenty of pages have an empty <main> shell with the real content injected into a sibling <div> by JavaScript; selecting the first matching container and getting 40 characters of skeleton is a real failure mode. The length check pushes the chain onward to a container that actually holds text.
Which strategy wins? It depends on the page type:
| Page type | Prune-first | Container-first | Notes |
|---|---|---|---|
| store.example.com product page | Keeps spec tables, reviews, Q&A — but also keeps filter sidebars if they are plain <div>s | Drops related-products carousels and cross-sell blocks that live outside the container; occasionally drops the spec table if it sits outside <main> | Product pages scatter content; pruning usually retains more |
| Blog post on example.com | Clean output, but keeps share-button rows and comment forms | Near-perfect: <article> wraps exactly the post body | Container-first wins decisively |
My opinionated recommendation: run both. Use container-first when the fallback chain resolves before body, and fall back to prune-first when it does not. A pipeline that tries container extraction and falls back to pruning handles both page types without per-site configuration, and per-site configuration is exactly what you are trying to avoid.
If you are fetching pages through a scraping API rather than running your own conversion, the same idea exists server-side: pass only_main_content: true on the scrape request and the boilerplate removal happens before the markdown is generated, so you never pay to ship the nav in the first place. That is one of the two or three settings I would call non-optional for any LLM-bound pipeline — the other is covered in Stop Cleaning HTML by Hand: Scrape Pages as Markdown.
Score Blocks by Text Density When the Markup Gives No Hints
Some pages have no <main>, no <article>, no role attributes, and a <div> soup where the nav and the content are visually distinct but structurally identical. This is where readability-style heuristics earn their keep.
The core insight, going back to the original readability research: main content is text-dense and link-poor. Navigation is link-dense and text-poor. You can score each top-level block on that basis:
import re
from bs4 import BeautifulSoup
LINK_TEXT_RE = re.compile(r"<a\b[^>]*>(.*?)</a>", re.S)
def strip_tags(fragment: str) -> str:
return re.sub(r"<[^>]+>", "", fragment)
def score_blocks(html: str, min_text: int = 120) -> str:
soup = BeautifulSoup(html, "html.parser")
root = soup.body or soup
kept = []
for block in root.find_all(recursive=False):
raw = str(block)
text = strip_tags(raw)
link_text = "".join(
strip_tags(m) for m in LINK_TEXT_RE.findall(raw)
)
score = len(text) - 2 * len(link_text) # links count double against the block
if score >= min_text:
kept.append(raw)
return "\n".join(kept)
The 2 * multiplier encodes the judgment call: a paragraph with one inline link survives easily, while a block that is mostly anchor text gets punished hard. Tune min_text against your token audit from section two — start at 120 and raise it until the boilerplate share stops dropping.
How do the approaches stack up on the same store.example.com fixture? Content recall is the share of real content sentences retained; boilerplate is the share of junk lines retained:
| Pipeline | Content recall | Boilerplate retained |
|---|---|---|
| html2text, raw | 100% | 100% |
| markdownify after DOM pruning | 97% | 11% |
| Trafilatura | 99% | 4% |
| readability-lxml | 96% | 9% |
Trafilatura wins on this fixture, and honestly it usually does — it combines DOM signals, text density, and learned rules, and I would reach for it before writing my own heuristics for anything production. Write your own scorer only when you need to debug or tune behavior per site, because a library’s opaque scoring is miserable to reason about when it silently drops a spec table. The trade-off discussion you might disagree with: I do not ship hand-rolled density scoring to production. It is a diagnostic tool and a fallback of last resort. The maintenance cost of tuned thresholds across a hundred different site templates exceeds the cost of just using a maintained library.
Configure the Converter Itself: strip and ignore Options in markdownify and html2text
DOM pruning and conversion are two separate steps, and they can drift: you prune nav in the DOM step but forget the converter’s own settings, and six months later someone “simplifies” the pruning code and the junk quietly returns. Belt and suspenders — configure the converter to suppress the same elements.
markdownify accepts a strip list of tags whose subtree is dropped during conversion:
from markdownify import markdownify as md
clean_md = md(
pruned_html,
strip=["nav", "footer", "aside", "form", "header", "iframe"],
heading_style="ATX", # # style, not underlined
bullets="-", # consistent bullet char
)
html2text has a different mechanism — an ignore set of tags whose contents are skipped entirely, versus its default behavior of keeping the text but dropping the markup:
import html2text
h = html2text.HTML2Text()
h.ignore_links = False # keep links in content
h.ignore_images = False
h.ignore_emphasis = False
h.body_width = 0 # no hard wrapping; keeps diffs clean
h.ignore_tags = {"nav", "footer", "aside", "header", "form", "script"}
before = html2text.html2text(nav_heavy_html) # default config
after = h.handle(nav_heavy_html) # configured
The diff on the example.com capture with a 10-item nav:
--- before
+++ after
-[Home](/) [Products](/products) [Pricing](/pricing) [Docs](/docs)
-[Blog](/blog) [About](/about) [Contact](/contact)
-[Careers](/careers) [Legal](/legal) [Status](/status)
# Example Product
Ten lines gone, content untouched. One warning about ignore_tags in html2text: it matches tag names only, so header also kills <header> used for a page’s <h1> on some sites. If your headings vanish, that is why — and it is another argument for doing the real work in the DOM, where you can select on attributes and context rather than bare tag names.
Post-Conversion Mop-Up: Regex Filters for Residual Menu Lines
Sometimes you do not control the conversion. Markdown arrives from a third-party source, a legacy pipeline, or a cache you cannot rebuild this week. Line-level cleanup is the last resort, and it is genuinely useful for three artifact classes: link-farm lines, repeated identical bullets, and “Skip to content” accessibility artifacts that leak when the skip link sits outside the pruned subtree.
import re
LINK_RE = re.compile(r"\[([^\]]*)\]\([^)]*\)")
BULLET_RUN_RE = re.compile(r"^(\s*[-*]\s+)(.+)\n(?:\1\2\n?)+", re.M)
SKIP_RE = re.compile(r"^\s*\[?skip to (content|main content)\]?.*$\n?", re.I | re.M)
def is_link_farm(line: str, threshold: float = 0.7) -> bool:
text = line.strip()
if len(text) < 20 or "[" not in text:
return False
non_link = LINK_RE.sub("", text)
return 1 - len(non_link.strip()) / len(text) > threshold
def mop_up(markdown_text: str) -> str:
lines = markdown_text.splitlines(keepends=True)
kept = [l for l in lines if not is_link_farm(l)]
out = "".join(kept)
out = BULLET_RUN_RE.sub(r"\1\2\n", out) # collapse identical bullet runs
out = SKIP_RE.sub("", out)
return re.sub(r"\n{3,}", "\n\n", out)
Now the failure mode, because it will bite you. Run this regex set over a documentation page and it deletes the reference list at the bottom — a legitimately link-dense block of real content. Same shape as a nav, same 70 percent link ratio, completely different meaning.
The guard is one clause: never apply the link-farm filter to the last section of the document, or more simply, require that a link-farm line also appear in the first or last 15 percent of the document. Menus live at the edges; reference lists live there too, but almost always under a heading. In practice the cheapest guard is positional:
def is_link_farm(line: str, pos: float, threshold: float = 0.7) -> bool:
if pos < 0.15 or pos > 0.85: # only hunt at document edges
# ... existing link-ratio check
return False # mid-document link lines are content
If you control the pipeline at all, prefer the DOM steps and treat this section as an emergency tool. Regex on markdown is operating on a representation that has already thrown away the information you need to make the decision safely.
Prove You Kept the Content: Diff the Cleaned Output Against a Readability Baseline
Every cleanup strategy has the same failure mode: it silently deletes real content. The spec table inside an <aside>. The reviews inside a pruned sidebar. You will not notice by eyeballing output, because the output looks cleaner — that is the trap. You need an automated recall check.
The approach: run Trafilatura (or any readability extractor you trust) as a baseline, extract its sentences, and verify each one survives in your cleaned markdown. Fail the pipeline if recall drops below a threshold.
import re, sys
import trafilatura
RECALL_THRESHOLD = 0.97
def sentences(text: str) -> list[str]:
text = re.sub(r"\s+", " ", text)
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if len(s.strip()) > 30]
def check_recall(html: str, cleaned_markdown: str) -> int:
baseline = trafilatura.extract(html) or ""
flat_clean = re.sub(r"\s+", " ", cleaned_markdown).lower()
refs = [s for s in sentences(baseline) if len(s) > 40]
if not refs:
print("no baseline sentences; skipping check")
return 0
missing = [s for s in refs if s.lower() not in flat_clean]
recall = 1 - len(missing) / len(refs)
print(f"sentence recall: {recall:.1%} ({len(missing)} missing of {len(refs)})")
for s in missing:
print(f" DROPPED: {s[:90]}...")
return 0 if recall >= RECALL_THRESHOLD else 1
if __name__ == "__main__":
html = open("fixtures/store_example_widget.html").read()
cleaned = open("output/cleaned.md").read()
sys.exit(check_recall(html, cleaned))
Wire this into your pipeline as a gate: nonzero exit blocks the run. On the example.com fixture, the prune-first pipeline scores:
sentence recall: 98.4% (2 missing of 125)
DROPPED: The extended warranty covers the motor for three years from the original purchase...
DROPPED: Customers who bought this item also considered the Widget Pro Max docking station...
The second drop is correct — that is cross-sell boilerplate Trafilatura happened to keep. The first is a real loss: the warranty note lived inside an <aside> on that page, and the blanket aside prune ate it. That is exactly the kind of finding that justifies the whole validation step, and the fix is site-aware: add a guard that spares aside nodes containing more than 200 characters of text, or switch that page class to container-first extraction.
Note the check is fuzzy by design — exact string matching on markdown would fail on formatting differences, hence the whitespace normalization and lowercase comparison. It is not perfect (a sentence split across two markdown blocks can be missed), but a 97 percent threshold catches gross content loss, which is what you are actually defending against.
Wrap-Up
Boilerplate in scraped markdown is not a converter bug — it is the converter faithfully doing its job on a DOM that was never structured for extraction. Fix it in the right order:
- Audit first. Token counts before and after, or you are flying blind.
- Prune the DOM (
nav,header,footer,aside,aria-hidden) before conversion. - Prefer container extraction when the fallback chain resolves; fall back to pruning when it does not.
- Use density scoring or Trafilatura for markup with no hints.
- Mirror the rules in converter options so the two steps cannot drift apart.
- Keep regex mop-up for edges and legacy input only, guarded positionally.
- Gate every run on a sentence-recall check against a readability baseline.
The recall gate is the piece most teams skip, and it is the cheapest insurance in the whole pipeline. If you are pushing this markdown into an LLM, also read Trim Scraped Pages Before They Flood the Agent Context for what to do on the consumption side, and Parse at Fetch Time vs Store Raw HTML before you decide to throw away the raw HTML that makes any of this re-runnable.
Related Articles
Identical Rows Fail to Join: Fix Unicode Normalization
Two scraped rows look identical but never join because the bytes differ. Spot NFC/NFD clashes, zero-width characters, and normalize keys before load.
TutorialYour Data Sits in an Iframe: Fix Extraction Across Frames
Your selector matches nothing, yet the data is visible in the browser. Here's why iframes break extraction and how to fetch frame content reliably.
TutorialYour Prices Parse as NaN: Fix Number Extraction
Scraped prices like '$1,299.00' become NaN after type conversion. Trace the parsing failure, normalize messy number formats, and fix it before load.