How to Escape HTML in Python
This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.
Python code
11 linesimport html
def escape_user_input(user_input: str) -> str:
"""Escape HTML-sensitive characters for safe display."""
return html.escape(user_input)
if __name__ == "__main__":
sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
safe_output = escape_user_input(sample_user_input)
print("Original:", sample_user_input)
print("Escaped: ", safe_output)
Output
Original: <script>alert("XSS")</script> & 'quotes'
Escaped: <script>alert("XSS")</script> & 'quotes'
How it works
The html.escape function converts special HTML characters like <, >, &, and ' into their corresponding HTML entities. This prevents the browser from interpreting user input as markup. The default behavior escapes quotes as well, which is important for attribute values. Using this utility is a straightforward way to mitigate XSS vulnerabilities when embedding user-generated content in web pages.
Common mistakes
- Using `html.escape` on already escaped input, causing double-encoding.
- Forgetting that the default `quote=True` escapes both single and double quotes, which may be overkill.
- Applying `html.escape` to entire HTML templates instead of just dynamic user input.
- Not escaping output when using frameworks that auto-escape, leading to inconsistent behavior.
Variations
- Use `html.escape(user_input, quote=False)` if you want to keep quotes unescaped.
- Use `markupsafe.escape()` (from Flask) when working in a web framework for additional context-aware escaping.
Real-world use cases
- Sanitizing user-submitted comments before rendering them in a web page to prevent script injection.
- Encoding form field values in HTML attributes so that quote characters don't break the markup.
- Preparing data for email templates that include user-provided names or messages.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.