Skip to content
GUIDE

How to Convert HTML to Markdown in Python, JavaScript and Node.js

The libraries worth using, what each one does to tables, code blocks and links, and why a whole web page needs main-content extraction before conversion. Every example was run against the same test page in November 2026.

Last updated

Short answer

To convert HTML to markdown in Python, use markdownify for HTML you control, or trafilatura to pull just the main content out of a web page. In Node.js, use Turndown with the turndown-plugin-gfm tables plugin, and run Mozilla Readability first on full pages. Pages built by JavaScript need a headless browser before any of these.

Converting a snippet of HTML is a one-liner in any language. Converting a real web page is harder: the page has navigation, a sidebar, a cookie banner, a footer and inline scripts, and a plain converter turns all of them into markdown. This guide covers both cases with code we ran against the same test page (an article with a language-python code block, a table and the usual page chrome), so the differences between libraries are ones we saw, not ones we read about.

Two different jobs: converting markup vs extracting a page

HTML-to-markdown tools fall into two groups, and most bad output comes from using the wrong one.

  • Converters (markdownify, html2text, Turndown) translate every element you give them. Give them an article body and you get a clean article. Give them a whole page and you get the menu, the footer links and, in our test, the text of an inline <script> tag.
  • Extractors (trafilatura, Readability, readability-lxml) first find the block of the page that holds the main content, then hand you just that. They're what you want for web pages, LLM input and RAG, and they occasionally pick the wrong block on unusual layouts.
  • A common pattern combines both: Readability or readability-lxml isolates the article as HTML, then a converter you've configured turns it into markdown.

HTML to markdown libraries compared

What each tool did with the same test page (November 2026, versions listed). Converters were given the whole page unless noted.
LibraryLanguageTypeDrops nav, footer, scriptsTablesCode-block languageRelative linksBest for
markdownify 1.2.4PythonConverterNo — remove them firstPipe tables with a header rowWith code_language_callbackLeft relativeFull control over conversion
html2text 2025.4.15PythonConverterNoCompact pipe tablesNo fences: code is indented 4 spacesMade absolute with baseurlQuick, readable text
trafilatura 2.4.0PythonExtractor + converterYesYes, on by defaultFence tagged python in our testMade absolute with url=Web pages to LLM or RAG input, with metadata
readability-lxml 0.9 + markdownifyPythonExtractor, then converterYesVia markdownifyWith code_language_callbackMade absolute with url=Article-style pages
Turndown 7.2.5 + turndown-plugin-gfm 1.0.2JavaScript (Node and browser)ConverterNo — remove() scripts, extract firstGFM tables when the first row is a header row; others stay HTMLFrom class="language-*"Left relativeThe standard JS converter
@mozilla/readability 0.6.0 + jsdom + TurndownNode.jsExtractor, then converterYesVia TurndownKept with keepClasses: trueMade absolute when jsdom gets urlFull web pages in Node
RenderKit /v1/extractHTTP APIBrowser render + extractor + converterYes (only_main_content, on by default)GFM tables with a header separatorKeptMade absoluteJavaScript-rendered pages, no infrastructure

Which one should you use?

  • Converting HTML you generated or already trimmed (CMS exports, emails, docs): markdownify in Python, Turndown in JavaScript.
  • Converting web pages for an LLM or a RAG index: trafilatura in Python, Readability + Turndown in Node. You get the article without the chrome, with absolute links.
  • Best HTML to markdown converter for Python, if you only pick one: trafilatura for web pages, markdownify for everything else. They solve different problems, so many projects use both.
  • Pages that render their content with JavaScript: none of the libraries run JavaScript. Render the page in a headless browser first, or use an API that does.

Convert HTML to markdown in Python

markdownify: the quick start

markdownify walks the HTML with BeautifulSoup and emits markdown. Two defaults are worth changing straight away: headings come out underlined (setext) unless you pass heading_style="ATX", and list bullets alternate between *, + and - by nesting depth unless you pass a single character.

markdownify_basic.py
# pip install markdownify
from markdownify import markdownify as md

html = """
<h1>Release notes 2.4</h1>
<p>Version <strong>2.4</strong> adds <a href="/docs/export">CSV export</a>.</p>
<ul><li>Exports keep column order.</li><li>Dates are ISO 8601.</li></ul>
"""

print(md(html, heading_style="ATX", bullets="-"))
output
# Release notes 2.4

Version **2.4** adds [CSV export](/docs/export).

- Exports keep column order.
- Dates are ISO 8601.

Other options you'll reach for: strip or convert to limit which tags are converted, escape_underscores and escape_asterisks (both on, so snake_case in text becomes snake\_case), table_infer_header for tables without a header row, and wrap for hard-wrapped paragraphs. Subclass MarkdownConverter and override a convert_<tag> method when you need custom output for one element.

Converting a whole web page with markdownify

Pointed at a full page, markdownify converts everything, including the <title> text and the body of every <script> tag. The fix is to clean the soup before converting it. This version also makes links absolute and keeps the language on fenced code blocks:

markdownify_page.py
# pip install requests beautifulsoup4 markdownify
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup
from markdownify import MarkdownConverter

url = "https://example.com/blog/release-notes"
resp = requests.get(url, headers={"User-Agent": "md-converter/1.0"}, timeout=20)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")

# 1. Delete page chrome. markdownify's strip= option removes the tag but keeps
#    its text, so <script> bodies would leak into the output.
for tag in soup(["script", "style", "noscript", "nav", "header", "footer", "aside", "form"]):
    tag.decompose()

# 2. Make links and images absolute, so they still work outside the page.
for a in soup.find_all("a", href=True):
    a["href"] = urljoin(url, a["href"])
for img in soup.find_all("img", src=True):
    img["src"] = urljoin(url, img["src"])


# 3. Keep the language on fenced code blocks: <pre><code class="language-python">
def code_language(pre):
    code = pre.find("code")
    for cls in (code.get("class", []) if code else []):
        if cls.startswith("language-"):
            return cls.removeprefix("language-")
    return None


converter = MarkdownConverter(
    heading_style="ATX",
    bullets="-",
    code_language_callback=code_language,
)
markdown = converter.convert_soup(soup.body or soup).strip()
print(markdown)
  • strip=["script"] is a trap: it removes the tag but keeps its text, so JavaScript ends up in your markdown. Delete unwanted elements with BeautifulSoup's decompose() instead.
  • Relative links like /docs/export mean nothing once the markdown leaves the page. urljoin against the page URL fixes them.
  • Syntax highlighters mark code with class="language-python" on the inner <code>. markdownify passes the <pre> to code_language_callback, so the callback looks one level down.
  • Deleting nav, header, footer and aside is a blunt rule. It works on most blogs and docs sites and fails on sites that put the article inside a <header>. For arbitrary sites, use an extractor.

trafilatura: main content in one call

trafilatura downloads a page, finds the main text and serializes it as markdown. In our test it was the only Python library that dropped the page chrome, made links absolute, tagged the code fence with its language and kept the table, all with default-ish settings:

trafilatura_example.py
# pip install trafilatura
import trafilatura

url = "https://example.com/blog/release-notes"
html = trafilatura.fetch_url(url)  # returns None if the download fails

markdown = trafilatura.extract(
    html,
    url=url,                   # resolves relative links
    output_format="markdown",
    include_links=True,
    include_tables=True,       # on by default; shown for clarity
    include_formatting=True,   # bold, italics, code
    with_metadata=True,        # YAML front matter: title, url, date, ...
)
print(markdown)
  • Tables and comments are included by default; formatting and images aren't. Pass include_comments=False on blogs, or reader comments end up in your output.
  • with_metadata=True adds YAML front matter with the title, URL, site name, description and a date. The date is a heuristic: on our test page it was read from the copyright line in the footer, so check it before you rely on it.
  • favor_precision=True returns less text when extraction is uncertain; favor_recall=True returns more. prune_xpath removes elements before extraction, for example a newsletter box the extractor keeps choosing.
  • fetch_url is a plain HTTP download: it doesn't run JavaScript, and it returns None on failure, so check the result before passing it on.

readability-lxml + markdownify

readability-lxml is a Python port of the Readability algorithm. It returns the article as cleaned HTML, which you convert with whatever markdownify settings you like. It keeps the article's <h1> and its class attributes, so pass the code_language_callback from the previous example if you want fenced languages.

readability_example.py
# pip install requests readability-lxml markdownify
import requests
from markdownify import markdownify as md
from readability import Document

url = "https://example.com/blog/release-notes"
resp = requests.get(url, headers={"User-Agent": "md-converter/1.0"}, timeout=20)
resp.raise_for_status()

doc = Document(resp.text, url=url)
title = doc.short_title()  # <title> without the " | Site name" suffix
article_html = doc.summary(html_partial=True)  # just the article <div>

markdown = md(article_html, heading_style="ATX").strip()
print(title)
print(markdown)

html2text

html2text is the oldest of the group and is still a fast way to get readable text out of HTML. It's a converter, so it keeps navigation and footers. It also hard-wraps lines at 78 characters unless you set body_width = 0, and it writes code blocks as indented text rather than fenced blocks, which loses the language. Its baseurl option makes links absolute.

html2text_example.py
# pip install html2text
import html2text

h = html2text.HTML2Text(baseurl="https://example.com/blog/release-notes")
h.body_width = 0        # don't hard-wrap lines at 78 characters
h.ignore_images = True

with open("page.html", encoding="utf-8") as f:
    print(h.handle(f.read()))

Convert HTML to markdown in JavaScript and Node.js

Turndown with GitHub-flavored tables

Turndown is the standard HTML-to-markdown library for JavaScript and runs in Node and the browser. Out of the box it writes setext headings, indented code blocks and * bullets, and it has no table support. Set the options below and add turndown-plugin-gfm for tables, strikethrough and task lists:

turndown_basic.mjs
// npm i turndown turndown-plugin-gfm
import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";

const turndown = new TurndownService({
  headingStyle: "atx",
  codeBlockStyle: "fenced",
  bulletListMarker: "-",
});
turndown.use(gfm); // tables, strikethrough, task lists
turndown.remove(["script", "style", "noscript"]);

const html = `
<h1>Release notes 2.4</h1>
<p>Version <strong>2.4</strong> adds <a href="/docs/export">CSV export</a>.</p>
<pre><code class="language-js">client.export({ format: "csv" });</code></pre>
<table>
  <thead><tr><th>Plan</th><th>Price</th></tr></thead>
  <tbody><tr><td>Hobby</td><td>$9</td></tr></tbody>
</table>`;

console.log(turndown.turndown(html));
  • The GFM plugin converts a table only when its first row is a header row. Tables without one are kept as raw HTML on purpose, because a markdown table needs a header.
  • remove() doesn't work on elements a built-in rule already handles, such as links: removal rules have the lowest precedence. Use addRule() with a replacement that returns an empty string instead.
  • Turndown also accepts a DOM node, so in a browser turndown.turndown(document.querySelector("article")) converts the live page without serializing it first.
  • On a whole page, Turndown included the <title> text and the inline script in our test. Call remove(["script", "style", "noscript"]), and extract the article first for anything you didn't write.

Full web pages: Readability + jsdom + Turndown

For arbitrary pages in Node, run Mozilla's Readability (the library behind Firefox Reader View) on a jsdom document, then convert the article HTML with Turndown:

readability_turndown.mjs
// npm i jsdom @mozilla/readability turndown turndown-plugin-gfm   (Node 18+)
import { JSDOM } from "jsdom";
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";

const url = "https://example.com/blog/release-notes";
const res = await fetch(url, { headers: { "user-agent": "md-converter/1.0" } });
if (!res.ok) throw new Error(`HTTP ${res.status}`);

// Passing `url` lets Readability rewrite relative links as absolute ones.
const dom = new JSDOM(await res.text(), { url });
// keepClasses keeps class="language-js" on code blocks so the fence gets a language.
const article = new Readability(dom.window.document, { keepClasses: true }).parse();
if (!article) throw new Error("Readability found no main content");

const turndown = new TurndownService({
  headingStyle: "atx",
  codeBlockStyle: "fenced",
  bulletListMarker: "-",
});
turndown.use(gfm);

// Readability usually drops the page's <h1> from `content`, so add the title back.
const markdown = `# ${article.title}\n\n${turndown.turndown(article.content)}`;
console.log(markdown);
  • Pass url to JSDOM. Readability uses the document's base URL to turn relative links and image sources into absolute ones.
  • parse() returns null when it can't find an article, which happens on home pages, search results and app shells. Handle that case instead of passing null to Turndown.
  • By default Readability strips class attributes, which removes the language-* class Turndown reads. keepClasses: true keeps them.
  • Readability removes a heading that duplicates the article title, so prepend article.title yourself. article.title is the page's <title>, which often ends in the site name.
  • Readability doesn't sanitize. Its README strongly recommends running untrusted output through a sanitizer such as DOMPurify before you render it as HTML. Markdown sent to an LLM doesn't need that, but markdown rendered back into a web page does.

These four elements cause most of the problems in converted markdown, whichever library you use.

  • Tables. Markdown tables need a header row and can't express merged cells (colspan, rowspan) or nested tables. Converters handle this differently: Turndown's GFM plugin leaves such tables as HTML, markdownify can promote the first row with table_infer_header, and layout tables used for positioning are better removed than converted.
  • Code blocks. The language usually lives in a language-* or lang-* class on <code> or <pre>. Make sure your extractor keeps classes and your converter reads them, or every fence comes out untagged. Converters also differ in whether blank lines inside a <pre> survive.
  • Links. Make them absolute (urljoin, jsdom's url, trafilatura's url=). Markdown that's going into an index or an LLM context gets separated from the page, and a relative link can't be cited or followed.
  • Images. Keep the alt text and drop the image when the reader is a language model: html2text's ignore_images, trafilatura's default, or a converter rule. Inline data: URIs can be enormous, so strip them before conversion.

HTML to markdown for LLMs and RAG

Markdown is the usual format for feeding web content to language models. It keeps the structure a model and a chunker can use (headings, lists, tables, code fences) and drops the markup that costs tokens without adding meaning. For LLM input, a few choices matter more than the library:

  • Extract the main content. Navigation and footer links repeated across every page of a site pollute retrieval results and waste context.
  • Use ATX headings (##). Chunkers split on them and they make good chunk titles.
  • Keep absolute links and record the source URL, so answers can cite the page.
  • Drop images and inline SVG, which contribute nothing a text model can read.

The full pipeline, from crawling and robots.txt to chunking and embeddings, is in web scraping for LLMs.

JavaScript-rendered pages need a browser first

Every library above works on the HTML it's given. On a single-page app or a client-rendered docs site, the HTML your HTTP client downloads is an empty shell and the content arrives later via JavaScript, so you get empty markdown. Render the page in a headless browser, wait for the element that holds the content, then convert the rendered DOM:

render_then_convert.py
# pip install playwright trafilatura && playwright install chromium
import trafilatura
from playwright.sync_api import sync_playwright

url = "https://quotes.toscrape.com/js/"  # the quotes are built by JavaScript

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto(url, wait_until="networkidle")
    page.wait_for_selector("div.quote")  # the element that holds the content
    html = page.content()  # the rendered DOM, not the original source
    browser.close()

print(trafilatura.extract(html, url=url, output_format="markdown", include_links=True))

In Node, the same pattern is await page.content() from Playwright or Puppeteer, then the Readability and Turndown code above. Waiting for a specific selector is more reliable than waiting for the network to go quiet: Playwright's own docs mark networkidle as discouraged. For finding a page's underlying JSON API, waits, infinite scroll and blocking, see how to scrape JavaScript websites.

HTML to markdown from the command line

All three Python libraries install a command-line tool, which is handy for one-off conversions and shell scripts:

terminal
# markdownify: convert a local file
markdownify page.html --heading-style atx > page.md

# html2text: same idea, no line wrapping
html2text --body-width 0 page.html > page.md

# trafilatura: download a URL and keep only the main content
trafilatura -u "https://example.com/blog/release-notes" --markdown --links --formatting

The one-call option: RenderKit /v1/extract

If you'd rather not run browsers or maintain extraction rules, RenderKit's extract endpoint does the whole chain in one request: it opens the URL in Chromium, waits for the page to settle (or for wait_for_selector), removes scripts, styles, navigation, headers, footers and sidebars, picks the main content block, and returns markdown with absolute links, language-tagged code fences and GFM tables.

POSTextract.sh
curl https://api.renderkit.tech/v1/extract \
  -H "x-api-key: $RENDERKIT_API_KEY" \
  -H "content-type: application/json" \
  -d '{ "url": "https://example.com/blog/release-notes", "format": "markdown" }'
extract.py
# pip install renderkit-sdk
import os

from renderkit import RenderKit

rk = RenderKit(os.environ["RENDERKIT_API_KEY"])

# A URL: rendered in Chromium, boilerplate removed, main content as markdown
doc = rk.extract(
    url="https://example.com/blog/release-notes",
    format="markdown",
    exclude_selectors=[".newsletter-signup", "#comments"],
)
print(doc["meta"]["title"], doc["meta"]["word_count"])
print(doc["content"])

# HTML you already have: the same cleanup and conversion, no fetch
with open("page.html", encoding="utf-8") as f:
    doc = rk.extract(html=f.read(), format="markdown")
extract.mjs
// npm i renderkit-sdk
import { RenderKit } from "renderkit-sdk";

const rk = new RenderKit(process.env.RENDERKIT_API_KEY);

const doc = await rk.extract({
  url: "https://example.com/blog/release-notes",
  format: "markdown",
});

if (doc.meta.blocked) throw new Error("The site served a bot-check page");
console.log(doc.meta.title, doc.meta.source_url);
console.log(doc.content);
  • Send url for a live page or html for markup you already have (up to 2 MB). The same cleanup and conversion run on both.
  • format can also be text or html (the cleaned main-content HTML). only_main_content: false converts the whole body; exclude_selectors removes elements you name before extraction.
  • chunk: true adds token-budgeted chunks for embeddings, on every plan.
  • Each extract costs 1 credit; repeat requests served from cache cost 0, and failed renders are refunded. The free trial includes 500 credits for 14 days with no card, and paid plans start at $9 a month for 5,000 credits.
  • It reads one URL per request and doesn't crawl or solve CAPTCHAs. When a site returns a bot-check page instead of content, the response says so with meta.blocked: true.

The full request and response reference, every parameter and a comparison with other hosted converters are on the URL to Markdown API page.

Build an ingestion pipeline: web scraping for LLMs and RAG. Get content out of dynamic sites: scrape JavaScript websites. Hosted options compared: best URL-to-markdown APIs in 2026. For agents: the RenderKit MCP server exposes extract as a tool.

Common questions

It depends on the input. For web pages, trafilatura is the strongest single choice: it extracts the main content, keeps tables, makes links absolute and returns markdown in one call. For HTML you control, such as CMS exports or emails, markdownify gives you the most control over the output. Many projects use both.

Install turndown and turndown-plugin-gfm, create a TurndownService with headingStyle set to atx and codeBlockStyle set to fenced, add the gfm plugin for tables, and call turndown() on your HTML string or a DOM node. For full web pages, run Mozilla Readability on a jsdom document first and convert article.content.

Download the page, extract the main content, then convert it. In Python, trafilatura.fetch_url plus trafilatura.extract with output_format set to markdown does all three. In Node, use fetch, jsdom and Readability, then Turndown. If the page builds its content with JavaScript, render it in a headless browser such as Playwright first, or use an API like RenderKit's /v1/extract that renders for you.

Converters such as markdownify, html2text and Turndown convert everything they are given, including navigation, footers and the text inside script tags. Remove those elements before converting, or use an extractor such as trafilatura or Readability that keeps only the main content.

markdownify produces fenced code blocks, standard pipe tables and lets you customize conversion per element, which makes it the better default. html2text is fine for quick, readable text, but it wraps lines at 78 characters unless you set body_width to 0 and it writes code as indented blocks without a language.

Make sure the table has a header row. In JavaScript, add turndown-plugin-gfm, which converts tables whose first row is a header row and leaves the rest as HTML. In Python, markdownify converts tables by default and can treat the first row as the header with table_infer_header, and trafilatura includes tables by default. Merged cells cannot be expressed in markdown.

Usually. Markdown keeps headings, lists, links and tables, which models and chunkers use, while dropping class names, scripts and styling markup that cost tokens without adding meaning. Converting only the main content also removes navigation and footer text that would otherwise repeat in every chunk.

Not with a plain HTTP download, because the content is not in the HTML the server sends. Load the page in a headless browser, wait for the content element to appear, take the rendered HTML and convert that. RenderKit's /v1/extract does the rendering and conversion in one API call.

Ship your first render in 60 seconds.

500 free credits to start. No card. Cancel by ignoring it.

Get your free key$npm i renderkit-sdk