HTML文件diff需先格式化再对比,推荐tidy或prettier标准化;浏览器端用diff2html可视化;Git中注意CRLF和BOM问题;语义级对比应使用lxml或html5lib解析DOM树。

用 diff 命令对比 HTML 文件最直接,但需先格式化
原始 HTML 常含空格、换行、缩进不一致,直接 diff a.html b.html 会因格式差异报大量“假不同”。必须先标准化再比对。
- 推荐用
tidy统一格式:tidy -indent -wrap 0 -quiet -asxhtml input.html > clean.html(注意加-asxhtml避免自闭合标签被重写) - 或用
prettier(需安装):prettier --parser html --print-width 120 a.html > a.prettier.html - Windows 用户若没装
tidy或prettier,可用 Python 快速清洗:python3 -c "import html.parser; import sys; print(open(sys.argv[1]).read().replace('&', '&').replace('\t', ' '))" a.html > a.clean.html(仅基础清理,不替代解析器)
浏览器里看 HTML 差异,highlight.js + diff2html 是轻量首选
不依赖后端、不上传代码,纯前端加载即可渲染带语法高亮的差异视图。
- 引入两个库:
<script src="https://cdn.jsdelivr.net/npm/diff2html@3.4.4/bundles/js/diff2html.min.js"></script>和<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/diff2html@3.4.4/bundles/css/diff2html.min.css"> - 用
diff命令生成统一的unified diff格式(即diff -u a.html b.html > diff.txt),再用Diff2Html.html(diffText)渲染到页面 - 注意:
diff2html默认不解析 HTML 标签内容,若需高亮 HTML 内联结构(如<div class="foo"> 中的 <code>class),得额外配置drawFileList: false并手动传入matching: 'lines'防止误合并git diff看 HTML 修改时,别忽略core.autocrlf和编码问题HTML 文件在 Git 中被当作文本处理,但 Windows 换行符(CRLF)和 UTF-8 BOM 常导致“无意义变更”刷屏。
- 检查当前设置:
git config --get core.autocrlf,推荐设为true(Windows)或input(macOS/Linux) - 确认文件无 BOM:
head -c 3 a.html | xxd,若输出含ef bb bf就是 BOM,用sed -i '1s/^\xEF\xBB\xBF//' a.html去除 - 强制 Git 按 HTML 处理:
echo "*.html text diff=html" >> .gitattributes,再配 Git 的diff.html.textconv = cat(实际作用有限,不如直接用diff2html可视化)
Python 脚本做语义级 HTML 对比,绕不开
lxml和html5lib想比“结构是否等价”(比如
<p>hello</p> <p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>和<p>\nhello\n</p>算相同),不能靠字符串 diff,得解析成 DOM 树再比。- 用
lxml解析并序列化为规范形式:from lxml import html; h1 = html.fromstring(open('a.html').read()); print(html.tostring(h1, encoding='unicode', method='html')) - 若 HTML 不规范(常见于手写或 CMS 输出),改用
html5lib:import html5lib; doc = html5lib.parse(open('a.html').read(), treebuilder='lxml'),再转lxml处理 - 注意:
lxml默认删注释、合并空白文本节点;如需保留,初始化时加remove_comments=False, remove_blank_text=False
lxml解析后归一化输出是最可控的路径。 - 检查当前设置:



















