html
The Python html
module provides utilities for manipulating HTML data, including escaping and unescaping HTML entities and tags.
This module is particularly useful when handling web data, as it ensures that special characters are correctly represented or interpreted in HTML documents.
Here’s an example:
>>> import html
>>> html.escape('<div class="content">Hello & Welcome!</div>')
'<div class="content">Hello & Welcome!</div>'
Key Features
- Escapes HTML special characters
- Unescapes HTML entities to regular characters
- Provides basic HTML manipulation utilities
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
html.escape() |
Function | Converts special characters to HTML-safe sequences |
html.unescape() |
Function | Converts HTML entities to their corresponding characters |
Examples
Escaping HTML special characters to ensure safe embedding in web pages:
>>> html.escape("5 > 3")
'5 > 3'
Unescaping HTML entities back to normal characters:
>>> html.unescape(""<div>Hello</div>")
'<div>Hello</div>'
Common Use Cases
- Safely embedding user-generated content into HTML pages
- Preparing HTML data for web scraping or parsing
- Converting HTML entities to plain text for processing
Real-World Example
Suppose you are building a web application that allows users to input text content, and you need to ensure that any HTML tags or entities in the input are safely escaped to prevent injection attacks:
>>> user_input = '<script>alert("Hacked!")</script>'
>>> safe_input = html.escape(user_input)
>>> print(safe_input)
'<script>alert("Hacked!")</script>'
By escaping the user input, the application prevents potentially harmful HTML or JavaScript from being executed in the browser, ensuring safe rendering of user content.
Related Resources
Tutorial
HTML and CSS for Python Developers
There's no way around HTML and CSS when you want to build web apps. Even if you're not aiming to become a web developer, knowing the basics of HTML and CSS will help you understand the Web better. In this tutorial, you'll get an introduction to HTML and CSS for Python programmers.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated July 9, 2025