Exporting to text

Once you have the node you want, to_markdown() turns it into GitHub-Flavored Markdown in one call, so a scraping script ends with Markdown instead of a tag soup:

import turbohtml

doc = turbohtml.parse("<article><h2>Tea</h2><p>Steep <em>green</em> tea for <b>3</b> minutes.</p></article>")
print(doc.find("article").to_markdown())
## Tea

Steep *green* tea for **3** minutes.

Pull out the article

A real page wraps that prose in navigation, sidebars and footers. When you only want the article and do not know its selector, main_content() finds the dominant content element for you by scoring the tree, and main_text() hands you its text directly:

page = turbohtml.parse(
    "<nav><a href='/'>Home</a></nav>"
    "<main class='post'><h2>Tea</h2>"
    "<p>Steeping green tea for three minutes draws out its flavor without turning it bitter.</p></main>"
    "<footer>(c) 2026</footer>"
)
print(page.main_content().tag)
print(page.main_text())
main
Tea

Steeping green tea for three minutes draws out its flavor without turning it bitter.

Sanitize a snippet

Export runs the other way too: when the HTML comes from someone else, clean it with turbohtml.clean.sanitize() before you embed it. The default policy keeps a safe subset of tags, drops event handlers and dangerous URL schemes, and escapes the elements it removes rather than discarding their text:

from turbohtml.clean import sanitize

print(sanitize('<a href="javascript:alert(1)">x</a> <b onclick="y()">bold</b><script>bad()</script>'))
<a>x</a> <b>bold</b>&lt;script&gt;bad()&lt;/script&gt;

Shrink the output

When you serialize a page to ship it, pass a Minify layout to drop the whitespace, optional tags and quotes the parser can put back. Hand its minify_js a JSMinify and inline <script> JavaScript is minified in the same pass, with local names renamed and constants folded:

from turbohtml import Html, Minify
from turbohtml.clean import JSMinify

doc = turbohtml.parse('<p>Hi</p>  <script>function greet(who) { return "hi " + who; }</script>')
print(doc.serialize(Html(layout=Minify(minify_js=JSMinify()))))
<p>Hi</p> <script>function greet(a){return"hi "+a}</script>

That is the whole tree API. Head to the How-to guides guides for task-focused recipes, the Migrating to turbohtml guide if you are coming from another HTML library, or the Reference for the exact signatures.