All articles

How to convert HTML to Markdown in JavaScript and Python

· 2 min read

Markdown is easier to edit, diff and store than HTML, and it's the input format for static site generators and most documentation tools. Converting HTML to Markdown comes up when migrating a CMS or a WordPress blog, archiving documentation, writing docs from existing pages, or preparing web content for language models.

JavaScript with Turndown

Turndown is the most widely used converter for JavaScript. It works in browsers and in Node.js:

npm install turndown @joplin/turndown-plugin-gfm
import TurndownService from "turndown";
import { gfm } from "@joplin/turndown-plugin-gfm";

const turndown = new TurndownService({
  headingStyle: "atx",       // "# Heading" instead of underlined headings
  codeBlockStyle: "fenced",  // ``` instead of indented code
  bulletListMarker: "-",
  emDelimiter: "*",
});
turndown.use(gfm);           // tables, strikethrough, task lists

const markdown = turndown.turndown(html);

For this input:

<h2>Install</h2>
<p>Run <code>npm i</code> and read the <a href="/docs">docs</a>.</p>
<ul><li>Fast</li><li><strong>Small</strong></li></ul>

Turndown produces:

## Install

Run `npm i` and read the [docs](/docs).

-   Fast
-   **Small**

The three spaces after - are Turndown's default list padding. It's valid Markdown, but most people write one space; a custom rule for li can change it.

Tables need the GFM plugin

Without a plugin, Turndown flattens a table into separate lines of cell text. With the GFM plugin:

| A   | B   |
| --- | --- |
| 1   | 2   |

Markdown tables can't express merged cells (colspan, rowspan) or block content inside cells, so complex tables may be kept as HTML or lose structure.

Remove page clutter

Converting a full page gives you navigation, footers, cookie banners and scripts. Remove them before converting:

turndown.remove(["script", "style", "nav", "footer", "aside", "form"]);

For articles, extracting the main content first works better. Mozilla's Readability (the library behind Firefox Reader View) does that:

import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";

const dom = new JSDOM(html, { url: pageUrl });
const article = new Readability(dom.window.document).parse();
const markdown = turndown.turndown(article.content);

Custom rules

Rules let you change how specific elements convert. For example, keep <iframe> embeds as raw HTML:

turndown.addRule("iframe", {
  filter: "iframe",
  replacement: (content, node) => `\n\n${node.outerHTML}\n\n`,
});

Python

markdownify

pip install markdownify beautifulsoup4
from bs4 import BeautifulSoup
from markdownify import markdownify as md

soup = BeautifulSoup(html, "html.parser")
for tag in soup(["script", "style", "nav", "footer"]):
    tag.decompose()  # remove the element and its contents

markdown = md(str(soup), heading_style="ATX", bullets="-")

markdownify's own strip option removes the tags but keeps their text, so a script's code would end up in the Markdown; removing the elements first avoids that.

markdownify converts tables to Markdown tables, and can be subclassed to customize the output for specific tags.

html2text

import html2text

h = html2text.HTML2Text()
h.body_width = 0          # don't wrap lines
h.ignore_images = False
markdown = h.handle(html)

html2text wraps lines at 78 characters by default, which creates noisy diffs; setting body_width = 0 turns wrapping off.

Pandoc

For batch conversions, Pandoc is a reliable command-line option:

pandoc page.html -f html -t gfm -o page.md

-t gfm outputs GitHub Flavored Markdown; elements that don't map to GFM are kept as raw HTML.

Common problems

Code blocks lose their language

HTML usually marks it with a class: <pre><code class="language-js">. Turndown's fenced style reads language-* classes. Syntax highlighters that wrap every token in <span> elements still convert to plain text correctly, but some put the language on <pre> or a wrapper <div>, which needs a custom rule.

Extra blank lines and escaped characters

Converters escape characters that would otherwise become Markdown syntax, such as *, _ and # at the start of a line, so 1. in a paragraph becomes 1\. . That's correct, but surprising. Whitespace-heavy HTML from page builders can also leave runs of blank lines; collapse them afterwards with markdown.replace(/\n{3,}/g, "\n\n").

<a href="/docs"> becomes [docs](/docs), which only works where the same paths exist. When moving content, resolve URLs against the original page:

for (const el of doc.querySelectorAll("a[href], img[src]")) {
  const attr = el.tagName === "A" ? "href" : "src";
  el.setAttribute(attr, new URL(el.getAttribute(attr), pageUrl).href);
}

Untrusted HTML

Converting doesn't make HTML safe: raw HTML that a converter keeps can still contain scripts when the Markdown is rendered later. Sanitize when rendering, as covered in the Markdown cheat sheet.

Checklist

  1. Extract the main content, or remove navigation, scripts and forms.
  2. Enable GFM for tables and strikethrough.
  3. Use ATX headings and fenced code blocks.
  4. Make links and image sources absolute, or copy images alongside.
  5. Review complex tables and embeds by hand.
  6. Sanitize when the resulting Markdown is rendered.

Frequently asked questions

Why do my tables come out as plain text?

Core Turndown has no table support. Add a GFM plugin (turndown-plugin-gfm or the maintained @joplin/turndown-plugin-gfm). Tables with merged cells or nested blocks still can't be represented in Markdown.

Can I convert a whole website?

Fetch each page, extract the main content (for example with Readability), convert it, and rewrite internal links to the new file paths. Respect the site's terms and robots rules.

Does the conversion keep images?

It keeps them as ![alt](src) links. Relative src values need to be made absolute or the images copied alongside the Markdown.

Is HTML to Markdown lossless?

No. Classes, styles, colors, layout and many attributes have no Markdown equivalent. Converters drop them or keep the raw HTML.

Further reading