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-sanitizerVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.
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).
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.
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`.
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.
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']}})`.