HTML to Markdown Converter — Python source
Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""html-to-markdown — supported HTML subset → Markdown converter. Python port
(canonical TS: src/lib/html-to-markdown.ts; Go twin:
cli/html-to-markdown/html-to-markdown.go). A hand-rolled single-scan tag
parser (no DOM) builds a node forest, then a renderer emits Markdown blocks:
h1-h6, p/div/blockquote, pre fences with the language taken from
class="language-*", ul/ol with 2-space (ul) and 4-space (ol) nested indent,
hr, br as two-spaces-newline; inline marks strong/b/em/i/del/s/code render
empty emphasis as nothing, links keep verbatim titles, images decode
alt/src. Unknown tags are transparent, stray closers are ignored, unclosed
tags auto-close at EOF, and text nodes backslash-escape \\ ` * _ [ ] so
literal characters cannot masquerade as Markdown. A '<' with no closing '>'
is the one error ("Unclosed tag").
Entities decode via html.unescape — the stdlib WHATWG table (the Python
counterpart of the TS lib's decodeHtml and Go's html.UnescapeString): full
named coverage plus numeric decimal/hex, single pass, no double-decode
("x &lt; y" stays "x < y"). Never raises — errors travel in the
result dict; empty or whitespace-only input is NOT an error.
"""
import html as _html
import re
VOID = {"br", "hr", "img", "meta", "link", "input", "source"}
BLOCK_TAGS = {
"p", "div", "blockquote", "pre", "ul", "ol", "hr",
"h1", "h2", "h3", "h4", "h5", "h6",
}
_TAG_NAME = re.compile(r"^([a-zA-Z][a-zA-Z0-9-]*)")
_ATTR = re.compile(r"([a-zA-Z-]+)(?:\s*=\s*(\"[^\"]*\"|'[^']*'|[^\s>]+))?")
_LANG_CLASS = re.compile(r"language-([\w-]+)")
_MD_ESCAPE = re.compile(r"[\\`*_\[\]]")
_WS_RUN = re.compile(r"\s+") # str patterns are unicode: \s covers U+00A0 too
class _Node:
"""One forest node: text (tag None) or element."""
__slots__ = ("tag", "attrs", "children", "text")
def __init__(self, text="", tag=None, attrs=None, children=None):
self.text = text
self.tag = tag
self.attrs = attrs if attrs is not None else {}
self.children = children if children is not None else []
def decode_entities(s):
"""One pass via the stdlib WHATWG table; malformed refs pass through."""
return _html.unescape(s)
def escape_markdown(s):
return _MD_ESCAPE.sub(lambda m: "\\" + m.group(), s)
def parse_html(raw):
"""Parse into a node forest. Attribute values may be double-quoted,
single-quoted or bare; a quoted value may contain '>'. Returns
(nodes, None) or (None, "Unclosed tag")."""
roots, stack = [], []
top = lambda: stack[-1].children if stack else roots
i = 0
while i < len(raw):
lt = raw.find("<", i)
if lt == -1:
top().append(_Node(text=raw[i:]))
break
if lt > i:
top().append(_Node(text=raw[i:lt]))
# Find the tag's '>', skipping quoted attribute values.
j = lt + 1
quote = None
while j < len(raw) and (raw[j] != ">" or quote is not None):
if quote is None and raw[j] in "\"'":
quote = raw[j]
elif quote is not None and raw[j] == quote:
quote = None
j += 1
if j >= len(raw):
return None, "Unclosed tag"
inner = raw[lt + 1:j].strip()
i = j + 1
if inner.startswith("!--"):
continue # comment
if inner.startswith("!"):
continue # doctype
closing = inner.startswith("/")
body = inner[1:] if closing else re.sub(r"/$", "", inner)
name = _TAG_NAME.match(body)
if not name:
continue # not a real tag — browsers would show it as text; we drop it
tag = name.group(1).lower()
if closing:
for k in range(len(stack) - 1, -1, -1):
if stack[k].tag == tag:
del stack[k:]
break
continue
attrs = {}
for am in _ATTR.finditer(body):
# Values stay RAW here; href/src/alt are entity-decoded at use,
# titles stay verbatim. The strip mirrors TS am[2].slice(1, -1):
# quoted values lose their quotes, bare values lose their first
# and last characters (same quirk the Go twin keeps for lock-step).
val = am.group(2)
attrs[am.group(1).lower()] = val[1:-1] if val else ""
elem = _Node(tag=tag, attrs=attrs)
top().append(elem)
if tag not in VOID and not body.endswith("/"):
stack.append(elem)
return roots, None
def _is_block(n):
return n.tag is not None and n.tag in BLOCK_TAGS
def render_inline(nodes):
"""Inline content of one block: marks, links, images, escaped text."""
out = []
for n in nodes:
if n.tag is None:
out.append(_WS_RUN.sub(" ", escape_markdown(decode_entities(n.text))))
elif n.tag == "br":
out.append(" \n")
elif n.tag in ("strong", "b"):
inner = render_inline(n.children).strip()
if inner:
out.append(f"**{inner}**") # empty emphasis renders as nothing
elif n.tag in ("em", "i"):
inner = render_inline(n.children).strip()
if inner:
out.append(f"*{inner}*")
elif n.tag in ("del", "s"):
inner = render_inline(n.children).strip()
if inner:
out.append(f"~~{inner}~~")
elif n.tag == "code":
inner = render_inline(n.children).strip()
if inner:
out.append(f"`{inner}`")
elif n.tag == "a":
href = decode_entities(n.attrs.get("href", ""))
title = f' "{n.attrs["title"]}"' if n.attrs.get("title") else ""
label = render_inline(n.children).strip() or href
out.append(f"[{label}]({href}{title})")
elif n.tag == "img":
alt = escape_markdown(decode_entities(n.attrs.get("alt", ""))).strip()
out.append(f")})")
else:
out.append(render_inline(n.children)) # span and unknown tags are transparent
return "".join(out)
def _text_of(nodes):
"""Concatenate the entity-decoded text under nodes (pre content only)."""
parts = []
for c in nodes:
parts.append(decode_entities(c.text) if c.tag is None else _text_of(c.children))
return "".join(parts)
def render_blocks(nodes):
"""Render a sequence of nodes as Markdown blocks."""
out, para = [], []
def flush():
if para:
text = render_inline(para).strip()
if text:
out.append(text)
para.clear()
for n in nodes:
if not _is_block(n):
para.append(n)
continue
flush()
if n.tag == "hr":
out.append("---")
elif n.tag == "p":
text = render_inline(n.children).strip()
if text:
out.append(text)
elif n.tag == "div":
out.extend(render_blocks(n.children))
elif n.tag == "blockquote":
inner = "\n\n".join(render_blocks(n.children))
out.append("\n".join(f"> {l}" if l else ">" for l in inner.split("\n")))
elif n.tag == "pre":
code_elem = next((c for c in n.children if c.tag == "code"), None)
lang = ""
if code_elem is not None:
lm = _LANG_CLASS.search(code_elem.attrs.get("class", ""))
if lm:
lang = lm.group(1)
source = code_elem if code_elem is not None else n
body = re.sub(r"\n+$", "", _text_of(source.children))
out.append("```" + lang + "\n" + body + "\n```")
elif n.tag in ("ul", "ol"):
out.append(render_list(n, 0))
else: # h1-h6
level = int(n.tag[1]) if n.tag[1].isdigit() else 0
out.append("#" * level + " " + render_inline(n.children).strip())
flush()
return out
def render_list(lst, depth):
"""ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
numbering restarted per list."""
items = [c for c in lst.children if c.tag == "li"]
ordered = lst.tag == "ol"
lines = []
for idx, li in enumerate(items):
marker = f"{idx + 1}." if ordered else "-"
indent = " " * (0 if depth == 0 else (4 if ordered else 2))
# Split li children into inline content + nested lists.
inline, nested = [], []
for c in li.children:
if c.tag in ("ul", "ol"):
nested.append(render_list(c, depth + 1))
else:
inline.append(c)
text = render_inline(inline).strip()
lines.append(f"{indent}{marker} {text}" if text else f"{indent}{marker}")
lines.extend(nested)
return "\n".join(lines)
def html_to_markdown(raw):
"""Convert the supported HTML subset to Markdown. Never raises — the
result dict carries output/error, mirroring HtmlToMarkdownResult."""
if not raw.strip():
return {"output": "", "error": None}
nodes, err = parse_html(raw)
if err:
return {"output": "", "error": err}
return {"output": "\n\n".join(render_blocks(nodes)), "error": None}
# Example:
# html_to_markdown('<h1>Title</h1><p>a & <b>b</b></p>')['output']
# → '# Title\n\na & **b**'
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →