pip install bleach
python
import bleach
dirty_text = '<p>This is <b>dirty</b> text.</p>'
clean_text = bleach.clean(dirty_text, strip=True)
print(clean_text)
python
import bleach
dirty_text = '<p>This is <b>dirty</b> text with <script>alert("malicious code");</script>.</p>'
allowed_tags = ['p', 'b']
allowed_attributes = {'b': ['style']}
clean_text = bleach.clean(dirty_text, tags=allowed_tags, attributes=allowed_attributes, strip=True, strip_comments=True)
print(clean_text)