48 of 51 hard targets returned a real page in production. Read the run

Blog / AI Agents

HTML to Markdown: Turning a Live Page into Clean Input for an LLM

Converting HTML to Markdown is easy. Getting Markdown worth feeding to a model is the hard part — most of the work happens before the converter runs.

Scrapengine Team//7 min read

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

JavaScript
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:

  1. No boilerplate removal. The converter faithfully converts everything, including the parts you want gone.
  2. 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.
  3. 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.

Shell
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.

Tip

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.

JavaScript
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:

JavaScript
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 ![](data:image/gif;base64,...), 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:

JavaScript
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:

Shell
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

Shell
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.

FAQ

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.

Keep reading

The pages you need are already refusing you

Start with a thousand pages. No proxy pool to rent, no browser fleet to run, and nothing billed for a wall we could not get through.