How to Use the HTML Tree Builder in Python
Tree construction in Aspose.HTML FOSS for Python implements the standards algorithm — insertion modes, error recovery, quirks detection, and foreign content — with parse_html() as the one-call entry point and TreeBuilder exposing the machinery. This guide explains the pipeline and its behaviours, using pip for installation.
Step-by-Step Guide
Step 1: Install the Package
pip install aspose-html-fossStep 2: Import Required Functions
from aspose_html.tree import parse_htmlStep 3: Parse Markup to a Tree
parse_html() runs the tokenizer and tree builder together, returning a finished tree; parse_fragment() applies the fragment algorithm against a context element. Both drive TreeBuilder.run() internally.
Step 4: Understand Construction State
InsertionMode models the algorithm’s mode machine, with StackOfOpenElements and TemplateInsertionModeStack tracking open elements and template modes exactly as the specification describes.
Step 5: Rely on Standards Error Recovery
Misnested formatting elements repair through run_adoption_agency_algorithm() with ActiveFormattingList tracking; misplaced table content foster-parents via get_foster_parent_location(); doctypes classify through determine_quirks_mode(); SVG/MathML attributes adjust via the adjust_*_attributes() functions.
Common Issues and Fixes
Bad markup produces a tree instead of an error. By design — the standards algorithm defines recovery for every error case.
Formatting tags appear duplicated. The adoption agency algorithm reconstructs formatting context after misnesting; the output matches browser behaviour.
Table content moved outside its table. Foster parenting relocated misplaced content; fix the nesting in the source markup.
Frequently Asked Questions
When should I use TreeBuilder directly instead of parse_html?
Only when you need construction-state introspection; parse_html() covers normal parsing.
How is quirks mode decided?
determine_quirks_mode() classifies the document from its doctype.
Does the builder handle SVG and MathML?
Yes — foreign content routes through the attribute adjusters with standards integration-point detection.