适用场景:批量替换 html 内文本、修改标签、增加头部 / 底部、修改属性、清理内容;无需额外安装包,只用 Python 内置库。
思路:遍历指定文件夹下所有 html 文件 → 读取文件内容 → 字符串替换 / 解析修改 → 写回文件。 两种方案:
- 简单字符串替换:适合简单文本替换,上手最快;缺点:不识别 HTML 标签结构,复杂 HTML 容易出错。
- BeautifulSoup 解析 HTML:推荐!可以精准修改标签、属性,能理解 HTML 结构,不容易改错。
准备工作
安装 bs4(方案 2 需要)
pip install beautifulsoup4
方案 1:简单字符串替换(适合简单文本替换)
新建 batch_replace_html.py
import os
# 配置
html_dir = r"./html_files" # html存放文件夹,相对路径
old_text = "旧文字"
new_text = "新文字"
# 遍历目录
for filename in os.listdir(html_dir):
if filename.lower().endswith((".html", ".htm")):
file_path = os.path.join(html_dir, filename)
# 读取
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# 替换
new_content = content.replace(old_text, new_text)
# 写回
with open(file_path, "w", encoding="utf-8") as f:
f.write(new_content)
print(f"已处理:{filename}")
print("全部完成!")
使用方法
- 新建文件夹
html_files,把所有 html 放进去 - 修改脚本里
old_text / new_text - 运行:
python batch_replace_html.py
⚠️ 缺点:只是纯文本替换,如果你要替换
href、class、标签内容,推荐 BeautifulSoup。
方案 2:BeautifulSoup 结构化修改 HTML【推荐】
可以精准:修改标签文字、修改属性、新增标签、删除标签。
示例 1:批量修改 a 标签的 href 链接
import os
from bs4 import BeautifulSoup
html_dir = r"./html_files"
for filename in os.listdir(html_dir):
if filename.lower().endswith((".html", ".htm")):
fp = os.path.join(html_dir, filename)
with open(fp, "r", encoding="utf-8") as f:
soup = BeautifulSoup(f.read(), "html.parser")
# 找到所有a标签
for a in soup.find_all("a"):
# 判断旧链接,替换href
if a.get("href") == "old.html":
a["href"] = "new.html"
# 保存回文件
with open(fp, "w", encoding="utf-8") as f:
f.write(str(soup))
print(f"处理完成:{filename}")
print("Done")
示例 2:批量修改所有 title 标题
import os
from bs4 import BeautifulSoup
html_dir = r"./html_files"
for filename in os.listdir(html_dir):
if filename.lower().endswith((".html", ".htm")):
fp = os.path.join(html_dir, filename)
with open(fp, "r", encoding="utf-8") as f:
soup = BeautifulSoup(f.read(), "html.parser")
# 修改title
if soup.title:
soup.title.string = "新网站标题"
with open(fp, "w", encoding="utf-8") as f:
f.write(str(soup))
print(filename)
示例 3:给所有 img 标签增加 alt 属性
for img in soup.find_all("img"):
img["alt"] = "图片描述"
示例 4:在 body 末尾追加一段 HTML 代码
from bs4 import BeautifulSoup
# ...
new_tag = BeautifulSoup('<div class="tip">底部新增文字</div>', "html.parser")
soup.body.append(new_tag)
重要备份建议(必看!)
修改前先备份全部 html 文件! 可以加一段备份代码,处理前自动复制一份到 backup 文件夹:
import shutil
# 备份文件夹
backup_dir = "./backup"
os.makedirs(backup_dir, exist_ok=True)
for filename in os.listdir(html_dir):
if filename.lower().endswith((".html", ".htm")):
shutil.copy2(os.path.join(html_dir, filename), os.path.join(backup_dir, filename))
print("✅ 备份完成")
递归遍历子文件夹(多层目录,常用)
上面脚本只处理一级目录,如果 html 在多层子文件夹,用 os.walk
import os
from bs4 import BeautifulSoup
html_dir = r"./html_files"
for root, dirs, files in os.walk(html_dir):
for name in files:
if name.lower().endswith((".html", ".htm")):
fp = os.path.join(root, name)
with open(fp, "r", encoding="utf-8") as f:
soup = BeautifulSoup(f.read(), "html.parser")
# 在这里写你的修改逻辑
# 示例:替换title
if soup.title:
soup.title.string = "新标题"
with open(fp, "w", encoding="utf-8") as f:
f.write(str(soup))
print(fp)
常见问题
- 乱码:文件编码不是 utf-8,尝试
encoding="gbk" - BeautifulSoup 格式化后 HTML 缩进变乱: 写入时可以用
soup.prettify(),但是会改动原有格式;如果不想改动原有换行缩进,纯字符串方案更合适。 - 特殊符号转义:bs4 会自动转义
& < >,如果不希望自动转义,需要其他库如 lxml。 - 文件权限:Linux 下注意文件读写权限。
两种方案怎么选
- 简单文字替换,不想改动 html 原有格式 → 字符串 replace
- 修改标签、属性、增删节点,HTML 结构复杂 → BeautifulSoup
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END











暂无评论内容