Dominate

2.9.1 · active · verified Sat Apr 11

Dominate is a Python library (current version 2.9.1) for creating and manipulating HTML documents using an elegant DOM API. It allows developers to write HTML pages concisely in pure Python, eliminating the need for a separate template language. The library is actively maintained with a regular release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a basic HTML document, adding elements to the head and body, nesting elements using `with` statements, and adding attributes including custom data attributes. It also shows how to explicitly add line breaks and handle raw text, highlighting a common 'gotcha' with newlines.

from dominate.document import document
from dominate.tags import html, head, body, h1, p, a, div, br
from dominate.util import text

doc = document(title='My Awesome Page')

with doc.head:
    a(href='https://example.com', _class='link-style', data_info='example') << 'Example Link'

with doc.body:
    h1('Hello, Dominate!')
    p('This is a paragraph created with Python.')
    with div(id='container'):
        p('Another paragraph inside a div.')
        p('Line one.')
        br()
        p('Line two with explicit break.')
        p('Raw text with newline:\n')
        text('This text should appear on a new line after the explicit break.')

# Render the document to an HTML string
html_output = doc.render()
print(html_output)

# Example of rendering with pretty printing off
# print(doc.render(pretty=False))

view raw JSON →