Transform HTML into a DOM model. Unique keys can be provided to HTML elements using a ``key=...`` attribute within your HTML tag. Parameters: html: The raw HTML as a string transforms: Functions of the form ``transform(old) -> new`` where ``old`` is a
(
html: str, *transforms: _ModelTransform, strict: bool = True
)
| 79 | |
| 80 | |
| 81 | def html_to_vdom( |
| 82 | html: str, *transforms: _ModelTransform, strict: bool = True |
| 83 | ) -> VdomDict: |
| 84 | """Transform HTML into a DOM model. Unique keys can be provided to HTML elements |
| 85 | using a ``key=...`` attribute within your HTML tag. |
| 86 | |
| 87 | Parameters: |
| 88 | html: |
| 89 | The raw HTML as a string |
| 90 | transforms: |
| 91 | Functions of the form ``transform(old) -> new`` where ``old`` is a VDOM |
| 92 | dictionary which will be replaced by ``new``. For example, you could use a |
| 93 | transform function to add highlighting to a ``<code/>`` block. |
| 94 | strict: |
| 95 | If ``True``, raise an exception if the HTML does not perfectly follow HTML5 |
| 96 | syntax. |
| 97 | """ |
| 98 | if not isinstance(html, str): # nocov |
| 99 | msg = f"Expected html to be a string, not {type(html).__name__}" |
| 100 | raise TypeError(msg) |
| 101 | |
| 102 | # If the user provided a string, convert it to a list of lxml.etree nodes |
| 103 | try: |
| 104 | root_node: etree._Element = fromstring( |
| 105 | html.strip(), |
| 106 | parser=etree.HTMLParser( |
| 107 | remove_comments=True, |
| 108 | remove_pis=True, |
| 109 | remove_blank_text=True, |
| 110 | recover=not strict, |
| 111 | ), |
| 112 | ) |
| 113 | except etree.XMLSyntaxError as e: |
| 114 | if not strict: |
| 115 | raise e # nocov |
| 116 | msg = "An error has occurred while parsing the HTML.\n\nThis HTML may be malformatted, or may not perfectly adhere to HTML5.\nIf you believe the exception above was due to something intentional, you can disable the strict parameter on html_to_vdom().\nOtherwise, repair your broken HTML and try again." |
| 117 | raise HTMLParseError(msg) from e |
| 118 | |
| 119 | return _etree_to_vdom(root_node, transforms) |
| 120 | |
| 121 | |
| 122 | class HTMLParseError(etree.LxmlSyntaxError): # type: ignore[misc] |