
Feeding raw HTML to a language model is expensive and bad. A typical article
page is 300–800 KB of markup, of which perhaps 3% is the text anyone wanted. The
rest is navigation, scripts, styles, tracking pixels, cookie banners, and three
layers of <div> wrapping each paragraph.
Markdown fixes the ratio. The same article is usually 5–15 KB of Markdown — an order of magnitude fewer tokens, with the structure that matters (headings, lists, links, code blocks, tables) preserved.
Converting HTML to Markdown is the easy part. Getting Markdown that is actually worth reading is mostly about what you do before the converter runs.
The naive version, and why it disappoints
import TurndownService from "turndown";
const turndown = new TurndownService();
const markdown = turndown.turndown(html);Run that on a real news article and you get the headline somewhere around line 400, preceded by the main navigation, a cookie notice, a newsletter prompt, a "related stories" rail, and the footer sitemap. Technically correct. Practically useless — and if you are paying per token, expensively so.
Three distinct problems:
- No boilerplate removal. The converter faithfully converts everything, including the parts you want gone.
- No JavaScript. Fetching HTML with an HTTP client gets you the server's first response. On a React or Vue site that is an empty shell, and your Markdown is a loading spinner.
- Lossy edge cases. Tables, nested lists,
<pre>blocks and inline SVG are where converters diverge. Defaults are rarely the ones you want.
Step one: get the rendered DOM, not the first response
This is the step most pipelines skip, and it is the one that decides whether you get content at all.
An HTTP client receives the HTML the server sent. A browser receives that, runs the JavaScript, and produces the DOM a human sees. On a client-rendered site these are completely different documents.
curl -X POST "https://api.scrapengine.io/api/v1/scrape" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/article",
"render": true,
"format": "markdown"
}'render: true runs the page in a real browser first. format: "markdown"
converts the result. One call, and the conversion happens against the DOM rather
than the shell.
Rendering costs more than fetching, so do not render by default. Fetch first, and escalate to a browser only when the result is suspiciously short or missing the selector you expect. On our own traffic roughly 60% of repeat requests are served without a browser at all.
Step two: strip boilerplate before converting
Remove the furniture at the DOM level, where you still have structural information, rather than trying to clean Markdown with regular expressions afterwards.
import { JSDOM } from "jsdom";
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";
const dom = new JSDOM(html, { url: pageUrl });
// Readability finds the article and discards the rest.
const article = new Readability(dom.window.document).parse();
const turndown = new TurndownService({
headingStyle: "atx", // ## Heading, not underlines
codeBlockStyle: "fenced", // ``` not four-space indents
bulletListMarker: "-",
emDelimiter: "_",
});
turndown.use(gfm); // tables, strikethrough, task lists
const markdown = turndown.turndown(article.content);Those four options are not cosmetic. headingStyle: "atx" keeps heading levels
unambiguous below <h2>, which underline style cannot express at all.
codeBlockStyle: "fenced" preserves the language hint; indented blocks lose it.
And without the GFM plugin, every <table> is converted to raw HTML inside your
Markdown, which puts the markup you were trying to escape straight back in.
If Readability is too aggressive — it sometimes discards documentation sidebars and API parameter tables you actually wanted — remove known furniture by selector instead:
const KILL = "nav, header, footer, aside, script, style, noscript, iframe, " +
"[role=navigation], [aria-hidden=true], .cookie-banner, .newsletter";
dom.window.document.querySelectorAll(KILL).forEach((el) => el.remove());Step three: fix the things converters get wrong
Relative links. [docs](/api/reference) is useless once the Markdown has
left the site. Resolve against the page URL before converting — passing url to
JSDOM above handles most of it, but check anchors and images.
Images you do not need. Tracking pixels and spacer GIFs become
, which can be kilobytes of noise each. Drop
images below a size threshold, and drop data: URIs entirely unless you want
them.
Whitespace. Converters emit runs of three or more blank lines around removed elements. Collapse them:
const clean = markdown
.replace(/\n{3,}/g, "\n\n")
.replace(/[ \t]+$/gm, "")
.trim();Code blocks. If the source marks language with class="language-python",
add a Turndown rule to carry it into the fence. A model reading your Markdown
benefits from knowing the language, and it is free to preserve.
Beyond HTML
Not everything you need to convert is a web page. PDFs, spreadsheets and Word
documents all show up in a real pipeline, and format: "markdown" handles
those too — the format is auto-detected, so the same call works:
curl -X POST "https://api.scrapengine.io/api/v1/scrape" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/whitepaper.pdf",
"format": "markdown",
"documentOptions": {
"pages": [1, 2, 3],
"stripHeadersFooters": true
}
}'stripHeadersFooters is the PDF equivalent of removing navigation: it drops the
repeated running header and page numbers that otherwise appear every few hundred
tokens and teach the model nothing.
A note on token economics
The reason to care is cost and attention, not neatness. Dropping a page from 400 KB of HTML to 8 KB of Markdown is roughly a 50× reduction in tokens. At scale that is the difference between a pipeline that is viable and one that is not — and shorter, cleaner context measurably improves what the model does with it, because the answer is no longer buried in a sitemap.
Try it
curl -X POST "https://api.scrapengine.io/api/v1/scrape" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/article", "render": true, "format": "markdown"}'Get a key at dashboard.scrapengine.io; the full parameter list is at docs.scrapengine.io.
Frequently asked questions
Use a converter such as Turndown with the GFM plugin for tables and strikethrough. The conversion itself is simple — the quality comes from removing navigation, scripts and banners at the DOM level first, and from rendering JavaScript so you convert the real document rather than an empty shell.
Related guides
- AI Agents5 min readBuilding AI Agents with Real-Time Web DataLearn how to give your AI agents access to structured, cited web data using Scrapengine's API — from search to extraction to dataset generation.
- HTTP7 min read403 Forbidden: Why a Scraper Gets One and What Actually Fixes ItWe audited every 403 in our production corpus. The browser fingerprint was almost never the cause — the exit address was. Here is how to tell which one you have.
- HTTP7 min read429 Too Many Requests: Reading Retry-After and Backing Off ProperlyA 429 is the one refusal that tells you how to fix it. Most clients ignore half the instruction — here is how to parse it, and when a 429 is not about rate at all.