给我一段代码,它能网页保存内容为mht文件
时间: 2024-04-29 16:26:12 浏览: 151
以下是使用Python的 requests 和 beautifulsoup4 模块实现将网页保存为mht文件的代码:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com" # 将此处的网址替换为你要保存的网页URL
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
html = soup.prettify()
mhtml_content = f"""Content-Type: multipart/related; boundary=boundary-example-1
--boundary-example-1
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
{html}
--boundary-example-1--"""
headers = {
"Content-Type": "application/x-mimearchive",
"Content-Disposition": "attachment; filename=index.mht",
}
with open("index.mht", "w", encoding="utf-8") as f:
f.write(mhtml_content)
print("mht文件保存成功!")
```
将代码中的 `url` 替换为你要保存的网页的URL,运行代码即可将网页保存为名为 `index.mht` 的文件。
阅读全文