html Library
HTML escaping and unescaping library, matching Python’s html module.
Import
import htmlAvailable Functions
| Function | Description |
|---|---|
escape(s) |
Escape HTML special characters |
unescape(s) |
Unescape HTML entities |
Functions
escape(s)
Escape HTML special characters in a string.
Converts:
&→&<→<>→>"→"'→'
Parameters:
s- String to escape
Returns: Escaped string
safe = html.escape("<script>alert('xss')</script>")
print(safe) # "<script>alert('xss')</script>"unescape(s)
Unescape HTML entities in a string.
Converts HTML entities back to their corresponding characters. Handles:
- Named entities:
<,>,&,",' - Numeric entities:
<,<
Parameters:
s- String with HTML entities to unescape
Returns: Unescaped string
text = html.unescape("<script>")
print(text) # "<script>"Examples
Sanitize User Input
import html
user_input = "<script>alert('xss')</script>"
safe_output = html.escape(user_input)
print(safe_output)
# Output: <script>alert('xss')</script>Build Safe HTML
import html
def create_element(tag, content):
safe_content = html.escape(content)
return "<" + tag + ">" + safe_content + "</" + tag + ">"
print(create_element("p", "Hello <world>"))
# Output: <p>Hello <world></p>Process HTML Entities
import html
# From API response
encoded = "Tom & Jerry"
decoded = html.unescape(encoded)
print(decoded) # "Tom & Jerry"Roundtrip Conversion
import html
original = '<div class="test">Content</div>'
escaped = html.escape(original)
restored = html.unescape(escaped)
print(original == restored) # TruePython Compatibility
escape(s)- ✅ Compatibleunescape(s)- ✅ Compatible
Note: Python’s html.escape() has an optional quote parameter (default True) which is not implemented. Our implementation always escapes quotes.