如果你想要自动规整化(格式化)HTML,可以使用以下方法:
方法 1:使用 VS Code 进行 HTML 格式化(推荐)
步骤
- 安装 Visual Studio Code
- 打开你的 HTML 文件
- 按下
Shift + Alt + F
(Windows/Linux)或Shift + Option + F
(Mac) - 你的 HTML 会自动格式化
插件推荐
如果默认格式化效果不够好,可以安装插件:
- Prettier - Code formatter(支持 HTML、CSS、JS)
- Beautify(专门优化 HTML 结构)
方法 2:使用命令行工具 tidy
(Linux/Mac/Windows)
如果你在服务器上处理 HTML,可以使用 tidy
工具。
安装 tidy
sudo apt install tidy # Ubuntu/Debian
brew install tidy-html5 # macOS
使用 tidy 进行 HTML 规整
tidy -indent -wrap 0 -modify input.html
选项说明:
-indent
自动缩进-wrap 0
不换行(保持长行)-modify
直接修改原文件
你可以在 tidy
之前加 cat
来查看格式化效果:
tidy -indent -wrap 0 input.html | cat
方法 3:使用 Python 进行 HTML 格式化
如果你更习惯编程,可以用 beautifulsoup4
来格式化 HTML。
安装依赖
pip install beautifulsoup4
格式化 HTML 代码
from bs4 import BeautifulSouphtml = """<html><body><h1>标题</h1><p>段落</p></body></html>"""soup = BeautifulSoup(html, "html.parser")
formatted_html = soup.prettify()print(formatted_html)
soup.prettify()
会自动格式化并加上缩进。
方法 4:在线 HTML 代码格式化
如果你不想安装工具,可以用在线格式化工具:
- https://htmlformatter.com/
- https://beautifier.io/
总结
方法 | 适用场景 | 复杂度 |
---|---|---|
VS Code 格式化 | 本地开发,简单高效 | ⭐ |
tidy 命令行 | 服务器端批量处理 | ⭐⭐ |
Python (BeautifulSoup) | 需要进一步解析和操作 HTML | ⭐⭐⭐ |
在线工具 | 只需要一次性格式化 | ⭐ |
如果你是开发者,VS Code + Prettier 或 tidy 是最方便的方式。如果需要自动化批量处理,Python 的 BeautifulSoup 更适合。🚀