import html import bleach # pip install bleach def sanitize_for_display(user_input_html): """ Sanitizes user-provided HTML content to prevent XSS attacks before displaying it on a web page. """ # Recommended tags and attributes that are generally safe. # Customize this list based on your application's needs. allowed_tags = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'p', 'strong', 'ul', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'span' ] allowed_attrs = { 'a': ['href', 'title'], 'abbr': ['title'], 'acronym': ['title'], } # Clean the HTML using bleach. # strip=True removes disallowed tags and their content. # If strip=False, disallowed tags are removed, but their content is kept. clean_html = bleach.clean( user_input_html, tags=allowed_tags, attributes=allowed_attrs, strip=True # Or strip=False if you want to keep content inside stripped tags ) return clean_html def escape_plain_text(user_input_text): """ Escapes special characters in plain text to prevent them from being interpreted as HTML. Use this for displaying text that should *never* contain HTML. """ return html.escape(user_input_text) # --- Example Usage --- # Scenario 1: User inputs potentially malicious HTML malicious_html_input = ( "" "
Hello, world!
Hello, world!
Click meHello, world!
This is great!
& that's all." escaped_text_output = escape_plain_text(plain_text_input) print(" --- Escaped Plain Text Output (for non-HTML content) ---") print(escaped_text_output) # Expected: "User's comment: <p>This is great!</p> & that's all."