Prompt
How to clean scraped web HTML to reduce LLM token costs in Node.js?
Latest observation
Clean scraped HTML by removing non-content DOM, extracting the main article, converting to Markdown/plain text, and normalizing whitespace before sending it to the LLM. In Node.js, a practical pipeline is cheerio for fast DOM pruning, optionally @mozilla/readability for article extraction, then node-html-markdown or turndown for compact Markdown.
Recommended pipeline
- Remove obvious noise:
<script>,<style>,<noscript>,<svg>,<iframe>,<form>, comments, cookie banners, nav, header, footer, and hidden elements. - Scope to the content container: prefer
<article>,<main>, or[role="main"]; fall back to<body>. - Strip attributes: remove
class,id,style,data-*, and event-handler attributes; retain only meaningful attributes such ashref,src,alt, andcolspan/rowspanwhen tables matter. - Convert to Markdown: preserve headings, lists, links, tables, and code blocks, since these often carry semantic value for LLMs.
- Normalize output: collapse repeated blank lines, trim whitespace, deduplicate navigation-like repeated text, and enforce a token/character budget.
Mozilla Readability is designed to remove navigation, ads, sidebars, and other page chrome, returning the article title, content, and metadata; in Node.js it requires a DOM such as jsdom.
Fast implementation
npm i cheerio node-html-markdown
import * as cheerio from "cheerio";
import { NodeHtmlMarkdown } from "node-html-markdown";
const NOISE_SELECTORS = [
"script", "style", "noscript", "svg", "iframe", "form",
"nav", "header", "footer", "aside",
"[role='navigation']", "[role='banner']", "[role='complementary']",
"[aria-hidden='true']", "[hidden]",
".cookie", ".cookies", "#cookie", ".consent", ".newsletter",
".advertisement", ".ad", ".social-share", ".related-posts"
].join(",");
const ALLOWED_ATTRS = new Set(["href", "src", "alt", "title", "colspan", "rowspan"]);
export function cleanHtmlForLlm(rawHtml, { maxLength = 30_000 } = {}) {
const $ = cheerio.load(rawHtml);
// 1. Remove non-content and boilerplate nodes.
$(NOISE_SELECTORS).remove();
$("comment").remove();
// 2. Prefer the semantic content container.
const root =
$("article").first().length ? $("article").first() :
$("main").first().length ? $("main").first() :
$("body");
// 3. Remove bulky attributes.
root.find("*").each((_, el) => {
if (el.type !== "tag" || !el.attribs) return;
for (const attr of Object.keys(el.attribs)) {
if (!ALLOWED_ATTRS.has(attr)) delete el.attribs[attr];
}
});
// 4. Convert only the cleaned fragment to Markdown.
const cleanedHtml = $.html(root);
const markdown = NodeHtmlMarkdown.INSTANCE.translate(cleanedHtml);
// 5. Normalize whitespace and cap the payload.
return markdown
.replace(/<!--[\s\S]*?-->/g, "")
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim()
.slice(0, maxLength);
}
This approach—pruning DOM subtrees before Markdown conversion—can reduce token usage dramatically while retaining headings, tables, code blocks, and most substantive facts. One benchmark reported a 90.6% reduction from 66,785 to 6,268 tokens while preserving 98.3% of ground-truth facts and all tested tables/code blocks.
When to use Readability
Use @mozilla/readability when pages are article-like and boilerplate is hard to identify with selectors. It scores candidate content blocks and extracts the main article, but is slower and more memory-intensive than direct Cheerio pruning.
npm i jsdom @mozilla/readability turndown turndown-plugin-gfm
import { JSDOM } from "jsdom";
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";
export function articleToMarkdown(html, url) {
const dom = new JSDOM(html, { url }); // URL helps resolve relative links
const article = new Readability(dom.window.document).parse();
const turndown = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced",
bulletListMarker: "-"
});
turndown.use(gfm);
return turndown
.turndown(article?.content ?? "")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
Pass the source URL to JSDOM so Readability can resolve relative links correctly.
Choose the right output
| Output | Best for | Token cost | Tradeoff |
|---|---|---|---|
| Plain text | Summarization, classification, simple Q&A | Lowest | Loses tables, code structure, links |
| Markdown | RAG, documentation, technical pages | Low–medium | Preserves structure and semantics |
| Cleaned HTML | Pages where exact DOM relationships matter | Medium | Usually more expensive than Markdown |
For most LLM workflows, clean Markdown is the best default: it is compact but retains headings, lists, links, code fences, and tables. html-to-text is a good alternative when you only need plain text.
Extra cost savings
- Deduplicate repeated blocks: site headers, breadcrumbs, and footers often repeat across pages.
- Drop images unless needed: keep
alttext only when it adds information. - Limit link text: convert long navigation lists into nothing, or retain only in-content links.
- Preserve tables selectively: keep tables for product specs, pricing, and data; otherwise convert them to short text.
- Chunk after cleaning: split Markdown by headings and target roughly 500–1,000 tokens per retrieval chunk.
- Measure with a tokenizer: log tokens before and after cleaning so you can catch pages where extraction accidentally removes useful content.
For JavaScript-rendered sites, remove page chrome in the browser with Playwright’s page.evaluate() before serializing the DOM, then run the same Markdown-conversion pipeline.
Citations
- https://chromium.googlesource.com/external/github.com/mozilla/readability/+/49bc5bfcc7704adc928dcd17e477fd36fd9f5679/README.md
- https://plainenglish.io/web-scraping/how-to-clean-scraped-web-html-to-reduce-llm-token-costs-by-90-in-nodejs-ykz1z6
- https://www.npmjs.com/package/html-to-text
- https://www.context.dev/blog/how-to-scrape-javascript-heavy-single-page-apps-into-llm-ready-markdown
- https://github.com/mozilla/readability
- https://openapps.pro/packages/mozilla-readability
- https://wtool.dev/guides/clean-html-to-markdown-llm-rag-token-optimization
- https://chromium.googlesource.com/external/github.com/mozilla/readability/+/refs/tags/0.4.1/README.md
- https://github.com/SbstnErhrdt/node-readability
- https://pypi.org/project/readabilipy/
- https://github.com/mozilla/readability/blob/main/Readability.js
- https://docs.rs/crate/readable-rs/latest