lxml-html-clean is a Python library that provides a robust HTML cleaning utility, originally part of the `lxml` project. It helps remove unwanted tags, attributes, and scripts from HTML content to sanitize it, protecting against XSS and other vulnerabilities. The current version is 0.4.4. It follows a low release cadence, typically for bug fixes or minor improvements.
Install & Compatibility
Where this runs
tested against v0.4.5 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Cleaner
✓ from lxml_html_clean import Cleaner
✗ from lxml_html_clean import HtmlCleaner
clean_html
✓ from lxml_html_clean import clean_html
autolink
✓ from lxml_html_clean import autolink
This quickstart demonstrates how to instantiate `HtmlCleaner` with specific configurations to sanitize HTML content, removing unwanted elements like scripts and iframes while preserving allowed tags and cleaning attributes. It highlights common configuration options for effective HTML sanitization.
from lxml_html_clean import HtmlCleaner
html_content = """
<html>
<head><title>Test</title></head>
<body>
<script>alert('xss');</script>
<p style="color:red;">Hello <b>World</b>!</p>
<a href="javascript:alert('bad');">Click me</a>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==">
<iframe></iframe>
</body>
</html>
"""
# Configure the cleaner to allow specific tags but remove scripts and styles
cleaner = HtmlCleaner(
allow_tags=['p', 'b', 'img'],
remove_tags=['script', 'iframe'],
kill_tags=['style'],
safe_attrs_only=True, # Remove potentially unsafe attributes
forms=False, # Remove form tags
scripts=True, # Remove script tags
comments=True, # Remove HTML comments
style=True, # Remove style tags
links=True, # Remove link tags (e.g., <link rel='stylesheet'>)
page_structure=False # Do not remove html, head, body tags
)
cleaned_html = cleaner.clean_html(html_content)
print("--- Original HTML ---")
print(html_content)
print("\n--- Cleaned HTML ---")
print(cleaned_html)
Debug
Known issues
deprecatedThe `lxml.html.clean.Cleaner` class, which provided HTML cleaning functionality directly within the `lxml` library, is now considered deprecated. Users are strongly encouraged to migrate to this standalone `lxml-html-clean` package for future maintenance and updates.fixReplace `from lxml.html.clean import Cleaner` with `from lxml_html_clean import HtmlCleaner`. Ensure `lxml-html-clean` is installed via `pip install lxml-html-clean`.
affects: lxml < 4.9.0 (functionality still exists but is superseded); lxml-html-clean all versions
gotchaThe `clean_html` method's return type is dynamic. If you pass a string as input, it returns a string. If you pass an `lxml.etree._Element` or `lxml.html.HtmlElement`, it returns an `lxml.html.HtmlElement`. This can be a footgun for type-sensitive code or when expecting a consistent output type.fixBe explicit about parsing and serializing if you need a specific type. If you need an `lxml` element back, parse the HTML with `lxml.html.fromstring` first, then clean the element, and serialize it back to a string with `lxml.html.tostring` if needed. Example: `tree = lxml.html.fromstring(html_str); cleaned_tree = cleaner.clean_html(tree); cleaned_str = lxml.html.tostring(cleaned_tree).decode()`.
affects: All versions
gotcha`HtmlCleaner` applies aggressive default cleaning settings (e.g., removing scripts, styles, links, comments, and unknown tags). If not explicitly configured, it might strip more content than desired. Users often need to precisely define `allow_tags`, `remove_tags`, `kill_tags`, `safe_attrs_only`, and other boolean flags.fixAlways review and configure `HtmlCleaner` parameters in its constructor (`HtmlCleaner(...)`) to match your exact content requirements and security policies. Start with a clear understanding of what you want to permit versus remove.
affects: All versions
Audit
Dependencies
lxmlrequiredCore dependency for HTML parsing and manipulation.