Prompt

How to clean scraped web HTML to reduce LLM token costs in Node.js?

Technology / Developer tools5 observationsLast seen Oct 30, 2026

Latest observation

Oct 30, 2026PerplexityWeb search: on

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

  1. Remove obvious noise: <script>, <style>, <noscript>, <svg>, <iframe>, <form>, comments, cookie banners, nav, header, footer, and hidden elements.
  2. Scope to the content container: prefer <article>, <main>, or [role="main"]; fall back to <body>.
  3. Strip attributes: remove class, id, style, data-*, and event-handler attributes; retain only meaningful attributes such as href, src, alt, and colspan/rowspan when tables matter.
  4. Convert to Markdown: preserve headings, lists, links, tables, and code blocks, since these often carry semantic value for LLMs.
  5. 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

OutputBest forToken costTradeoff
Plain textSummarization, classification, simple Q&ALowestLoses tables, code structure, links
MarkdownRAG, documentation, technical pagesLow–mediumPreserves structure and semantics
Cleaned HTMLPages where exact DOM relationships matterMediumUsually 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 alt text 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.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (5 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.