Registry / serialization / html-sanitizer

html-sanitizer

JSON →
library2.6.0pypypi✓ verified 21d ago

This is an allowlist-based and very opinionated HTML sanitizer for Python, designed to clean up HTML fragments from untrusted or trusted sources. It's built upon `lxml` to ensure valid and safe HTML output. Beyond basic tag and attribute allowlisting, it applies additional transforms to normalize and simplify HTML content, aiming for consistency, especially from rich text editors. It's actively maintained.

pip install html-sanitizer
INSTALL
IMPORT
SIG · HTML-SANITIZER
H
html-sanitizer
serializationpythonv2.6.0
Install
2.4s avg
Import
88ms
Disk
29MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.6.0 · 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
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.088s · 31.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.088s · 32MB
29MB installed
● package 29MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Sanitizer
from html_sanitizer import Sanitizer

Initialize a `Sanitizer` object (with or without custom settings) and call its `sanitize` method with the dirty HTML string. The default configuration is restrictive, only allowing a specific set of tags and attributes.

from html_sanitizer import Sanitizer sanitizer = Sanitizer() # Uses default configuration dirty_html = '<p>Hello <script>alert("XSS")</script>World!</p><span style="font-weight:bold">some text</span>' safe_html = sanitizer.sanitize(dirty_html) print(safe_html) # Example with custom configuration custom_sanitizer = Sanitizer({ 'tags': {'p', 'h1', 'a'}, 'attributes': {'a': ('href', 'title')}, 'empty': set(), 'separate': set(), }) custom_dirty_html = '<h1>Title</h1><p>Some text. <a href="/link">Link</a> <img src="x.jpg"> </p>' custom_safe_html = custom_sanitizer.sanitize(custom_dirty_html) print(custom_safe_html)
Debug
Known issues
gotchaThe library is strictly allowlist-based and 'opinionated'. By default, many common HTML elements (like `div`, `img`) and all inline styles and scripts are removed, even if not explicitly malicious. Users must configure the `Sanitizer` instance to allow more tags/attributes.
fix
Always review the default `Sanitizer` settings. Customize `tags`, `attributes`, and other options when initializing `Sanitizer` to fit your specific use case. Refer to the documentation for available settings.
affects: All versions
breakingA security vulnerability (CVE-2024-34078) was identified where specific unicode characters, when normalized, could bypass sanitization if `keep_typographic_whitespace=False` (which is the default behavior). This could lead to XSS attacks.
fix
Upgrade to version 2.4.2 or higher to receive the fix for this vulnerability. Ensure your deployment pipelines automatically update or flag vulnerable versions.
affects: <2.4.2
gotchaThe `Sanitizer` constructor performs consistency checks on provided settings. If there are conflicts (e.g., a tag is marked as `empty` but not in the `tags` allowlist), a `TypeError` will be raised.
fix
Carefully define your `Sanitizer` settings to ensure logical consistency. For instance, any tag listed in `empty` or `separate` must also be present in the `tags` allowlist.
affects: All versions
gotchaHTML comments are stripped by default. If preserving comments is necessary, this behavior needs to be explicitly overridden, though generally, comments in user-generated content are not considered safe.
fix
While generally recommended to strip comments for security and cleanliness, if you must preserve them, check the `Sanitizer` documentation for an option to retain them (e.g., `strip_comments=False` if available in your version's configuration).
affects: All versions
Errors
Common errors & fixes
TypeError: Inconsistent settings found in Sanitizer configuration
The `html-sanitizer` library raises a `TypeError` when the provided configuration for `Sanitizer` contains inconsistencies, such as a tag being listed as 'empty' but not present in the general 'tags' allowlist.
fix
Ensure that your `Sanitizer` configuration settings are consistent. For example, any tag specified in the 'empty' set must also be present in the 'tags' set. Review the `html-sanitizer` documentation for valid configuration structures.
ImportError: cannot import name 'Sanitizer' from 'html_sanitizer'
This error often occurs due to version conflicts or issues with `lxml`, which `html-sanitizer` depends on, or an incorrect import statement. A common scenario is an `lxml` version mismatch with the installed `html-sanitizer` version.
fix
First, ensure you have `html-sanitizer` installed: `pip install html-sanitizer`. If the error persists, try upgrading or reinstalling `lxml` and `html-sanitizer` to resolve potential dependency conflicts: `pip install --upgrade lxml html-sanitizer`. Also, verify the import statement is `from html_sanitizer import Sanitizer`.
My inline styles are being removed by html-sanitizer (or script tags)
The `html-sanitizer` library is designed to be very opinionated and, by default, strictly disallows and removes all inline styles and `<script>` tags for security reasons, regardless of other tag or attribute configurations.
fix
This is expected behavior and a core security feature of the library. If you need specific styling, apply it through external CSS. For scripts, consider alternative ways to implement functionality without embedding raw JavaScript in the HTML, as the sanitizer is not intended to allow it. There is no direct configuration to 'allow' inline styles or script tags within this library.
Certain HTML tags or attributes are unexpectedly removed after sanitization
The `html-sanitizer` uses an allowlist-based approach, meaning only tags and attributes explicitly listed in its configuration (or defaults) will be preserved. If a tag or attribute is missing from these allowlists, it will be removed.
fix
Customize the `Sanitizer` instance by providing explicit `tags` and `attributes` allowlists in its constructor to include all the elements and attributes you intend to keep. For example, to allow `<img>` tags with `src` and `alt` attributes: `sanitizer = Sanitizer({'tags': {'img'}, 'attributes': {'img': ['src', 'alt']}})`.
Upgrade
Version history
2.6.0latest on PyPI · released Jun 30, 2025
Audit
Dependencies
lxmlrequiredCore parsing and cleaning functionality relies on lxml's HTML cleaner.
Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
1
Resources
html-sanitizer — pip install html-sanitizer · libregistry