The html_to_unicode function is a high-level utility that converts raw HTML bytes into a Unicode string by attempting to guess the encoding using the following priority:
- BOM (Byte Order Mark): If present, it is used and stripped.
- HTTP Content-Type header: If provided.
- Meta or XML tag declarations: Found in the HTML body.
- Auto-detection: If an
auto_detect_fun is provided. - Default encoding: Specified by
default_encoding (defaults to 'utf8').
This method is robust and will not fail on decoding errors; instead, it inserts the Unicode replacement character � for invalid sequences.
To use an external library like chardet for auto-detection, pass it via auto_detect_fun.
import w3lib.encoding
# Example with meta tag detection
html_to_unicode(
content_type_header=None,
html_body_str=b"<html><head><meta charset='UTF-8' /></head><body></body></html>"
)
# returns ('utf-8', '<html><head><meta charset="UTF-8" /></head><body></body></html>')
# Example using chardet for auto-detection
import chardet
html_to_unicode(
content_type_header=None,
html_body_str=b'\xec\x9a\x9c...',
auto_detect_fun=lambda x: chardet.detect(x).get('encoding')
)