MHTML Format (MIME HTML)
Description
MHTML (MIME HTML) is a format for archiving web pages. It combines HTML content with embedded resources (images, CSS, JavaScript) into a single file using MIME multipart encoding. MHTML files are used by Internet Explorer and other browsers for saving complete web pages.
File Extensions
.mhtml- MHTML archive files.mht- MHTML archive files (alias)
Implementation Details
Reading
The MHTML implementation:
- Uses Python's built-in
emailmodule - Parses MIME multipart format
- Extracts HTML content and embedded resources
- Converts each part to a dictionary
- Handles content types and locations
- Extracts main HTML content
Writing
Writing support:
- Writes a multipart/related MHTML document
- Uses
contentormain_contentas the HTML part
Key Features
- Web archive format: Designed for archiving web pages
- Multipart MIME: Uses MIME multipart encoding
- Resource embedding: Embeds images, CSS, JavaScript
- Nested data: Supports complex web content structures
- Content extraction: Extracts HTML and resources
Usage
from iterable import open_iterable
# Basic reading
with open_iterable('page.mhtml') as source:
for part in source:
print(part) # Contains content type, location, and content
# Writing
with open_iterable('output.mhtml', mode='w') as dest:
dest.write({'subject': 'Page', 'content': '<html><body>Hi</body></html>'})
Parameters
encoding(str): File encoding (default:utf8)
Limitations
- Web archive focus: Designed for web page archiving
- Complex structure: Multipart MIME structure can be complex
- Memory usage: Large web pages may use significant memory
Compression Support
MHTML files can be compressed with all supported codecs:
- GZip (
.mhtml.gz) - BZip2 (
.mhtml.bz2) - LZMA (
.mhtml.xz) - LZ4 (
.mhtml.lz4) - ZIP (
.mhtml.zip) - Brotli (
.mhtml.br) - ZStandard (
.mhtml.zst)
Use Cases
- Web archiving: Archiving complete web pages
- Web scraping: Saving web page content
- Offline browsing: Storing web pages for offline viewing
- Content preservation: Preserving web content
Error Handling
- Missing dependency: optional libraries raise
ImportErrorwith an install hint (pip install 'iterabledata[<extra>]'when an extra exists). - Write mode: read-only formats raise
WriteNotSupportedErrororValueErrorwhen opened withmode="w". - Bad or unsupported input: may raise
ValueError,OSError, or library-specific errors. - See Troubleshooting for decoding, detection, and engine issues.