如何使用Python调用wget将本地HTML网页转换为MHTML格式
实现方案
首先需要纠正你的思路:wget是用于网络资源下载的工具,本身不支持解析本地HTML关联资源并导出MHTML格式,也没有必要用它读取本地文件。以下是两种可直接在Python中实现的可行方案:
方案1:无头浏览器生成(兼容性最优,推荐)
利用Chrome/Edge浏览器原生支持导出MHTML的能力,完全复刻你直接打开网页的显示效果,不会出现资源加载遗漏、样式错乱的问题。
步骤1:安装依赖
pip install selenium webdriver-manager
步骤2:代码实现
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import os # 配置无头Chrome参数 chrome_options = Options() chrome_options.add_argument("--headless=new") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--allow-file-access-from-files") # 允许读取本地资源 # 启动浏览器 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options) # 本地HTML文件转file协议URL local_html_path = os.path.abspath("mypage.html") file_url = f"file://{local_html_path}" # 加载网页 driver.get(file_url) # 等待所有资源加载完成,可根据页面复杂度调整时长 driver.implicitly_wait(5) # 导出MHTML mhtml_content = driver.execute_cdp_cmd("Page.captureSnapshot", {"format": "mhtml"})['data'] # 保存到本地 with open("output.mhtml", "w", encoding="utf-8") as f: f.write(mhtml_content) driver.quit()
说明
- 如果你用Edge浏览器,把
Chrome相关的导入替换为Edge即可,webdriver-manager会自动适配对应驱动 - 生成的
output.mhtml是单文件,所有CSS、JS、图片资源都已内嵌,可直接用浏览器打开,也可作为邮件附件发送
方案2:纯Python库生成(无浏览器依赖)
如果不想安装浏览器,可使用py-mhtml库手动解析关联资源并打包,适合结构简单、无动态JS生成内容的页面
步骤1:安装依赖
pip install py-mhtml
步骤2:代码实现
from mhtml import MHTML import os m = MHTML() # 添加主HTML文件 m.add_file(os.path.abspath("mypage.html"), "text/html") # 遍历资源文件夹添加所有关联资源 resource_dir = "mypage_files" for root, dirs, files in os.walk(resource_dir): for file in files: file_path = os.path.join(root, file) # 自动判断资源类型,也可手动指定 if file.endswith(".css"): mime_type = "text/css" elif file.endswith((".png", ".jpg", ".jpeg", ".gif")): mime_type = f"image/{os.path.splitext(file)[1][1:]}" elif file.endswith(".js"): mime_type = "application/javascript" else: mime_type = "application/octet-stream" m.add_file(file_path, mime_type) # 导出MHTML with open("output.mhtml", "wb") as f: f.write(m.generate())
说明
- 该方案对动态JS生成的内容无法识别,适合静态页面使用
- 复杂页面可能出现样式、资源引用错误,优先推荐方案1
内容的提问来源于stack exchange,提问作者ℕʘʘḆḽḘ
相关产品推荐
相关产品推荐

