使用 Python 批量在 HTML 文件中插入自定义 div 元素

适用人群:前端开发者、Python 自动化脚本初学者、网站维护人员

在日常开发或网站维护中,我们经常需要对大量 HTML 文件进行统一修改,比如添加导航栏、公告条、统计代码等。手动一个个修改不仅效率低,还容易出错。本文将教你如何使用 Python + BeautifulSoup 编写脚本,批量在 HTML 文件中插入自定义 <div> 元素,并提供两种常见场景的实现方式。


一、准备工作

1. 安装依赖库

确保你已安装 beautifulsoup4

bash 复制代码
pip install beautifulsoup4

注意:本教程使用 html.parser(Python 内置解析器),无需额外安装 lxml 或 html5lib。

2. 目录结构示例

假设你的项目结构如下:

复制代码
your_project/
├── pages/
│   ├── index.html
│   ├── about.html
│   └── contact.html
└── add_div_script.py  ← 脚本文件

我们将对 pages/ 文件夹下的所有 .html 文件进行处理。


二、场景一:在 <body> 开头插入 div

适用于没有 <header> 标签,或希望统一在 body 最顶部插入内容的场景(如全局公告条)。

✅ 脚本代码

python 复制代码
from bs4 import BeautifulSoup
import os

def add_div_to_html_files_in_folder(folder_path, class_name, content):
    """
    遍历指定文件夹下所有 .html 文件,在 <body> 的最开始位置插入一个 div。
    
    参数:
        folder_path (str): HTML 文件所在文件夹路径
        class_name (str): 新 div 的 class 类名
        content (str): 新 div 的文本内容
    """
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.html'):
                html_file = os.path.join(root, file)

                # 读取 HTML 文件
                with open(html_file, 'r', encoding='utf-8') as f:
                    html_content = f.read()

                soup = BeautifulSoup(html_content, 'html.parser')

                # 创建新的 div 标签
                new_div = soup.new_tag('div', attrs={'class': class_name})
                new_div.string = content

                # 找到 body 标签,并在开头插入新 div
                body_tag = soup.body
                if body_tag:
                    body_tag.insert(0, new_div)

                # 写回文件
                with open(html_file, 'w', encoding='utf-8') as f:
                    f.write(str(soup))

# 配置参数
folder_path = './pages'          # 替换为你的 HTML 文件夹路径
class_name = 'my_nav'
content = '欢迎大家访问'

# 执行函数
add_div_to_html_files_in_folder(folder_path, class_name, content)
print("✅ 已在所有 HTML 文件的 <body> 开头插入 div!")

📌 效果示例

原 HTML:

html 复制代码
<body>
  <h1>首页</h1>
  <p>内容...</p>
</body>

处理后:

html 复制代码
<body>
  <div class="my_nav">欢迎大家访问</div>
  <h1>首页</h1>
  <p>内容...</p>
</body>

三、场景二:在 <header> 前插入 div

适用于有语义化 <header> 标签的现代网页,希望在 header 之前插入内容(如顶部通知栏)。

✅ 脚本代码

python 复制代码
from bs4 import BeautifulSoup
import os

def insert_div_before_header_in_html_files(folder_path, class_name, content):
    """
    遍历 HTML 文件,在 <header> 标签前插入 div;
    若无 <header>,则退回到在 <body> 开头插入。
    """
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.html'):
                html_file = os.path.join(root, file)

                with open(html_file, 'r', encoding='utf-8') as f:
                    html_content = f.read()

                soup = BeautifulSoup(html_content, 'html.parser')

                # 创建新 div
                new_div = soup.new_tag('div', attrs={'class': class_name})
                new_div.string = content

                # 查找 header 标签
                header_tag = soup.find('header')
                if header_tag:
                    header_tag.insert_before(new_div)  # 插入到 header 前
                else:
                    # 回退方案:插入到 body 开头
                    body_tag = soup.body
                    if body_tag:
                        body_tag.insert(0, new_div)

                # 保存修改
                with open(html_file, 'w', encoding='utf-8') as f:
                    f.write(str(soup))

# 配置参数
folder_path = './pages'
class_name = 'my_nav'
content = '欢迎大家访问'

# 执行
insert_div_before_header_in_html_files(folder_path, class_name, content)
print("✅ 已在 <header> 前(或 body 开头)插入 div!")

📌 效果示例

原 HTML:

html 复制代码
<body>
  <header>
    <h1>网站标题</h1>
  </header>
  <main>...</main>
</body>

处理后:

html 复制代码
<body>
  <div class="my_nav">欢迎大家访问</div>
  <header>
    <h1>网站标题</h1>
  </header>
  <main>...</main>
</body>

四、注意事项 & 最佳实践

  1. 备份原始文件

    脚本会直接覆盖原文件!建议先复制一份备份,或在测试目录运行。

  2. 编码问题

    使用 encoding='utf-8' 可避免中文乱码,确保你的 HTML 文件也是 UTF-8 编码。

  3. 路径设置
    folder_path 支持相对路径(如 './pages')或绝对路径(如 '/Users/name/project/html')。

  4. 扩展性

    • 可将 content 改为 HTML 字符串(使用 new_div.append(BeautifulSoup(html_str, 'html.parser'))
    • 可添加更多属性,如 idstyle 等:attrs={'class': 'xxx', 'id': 'yyy', 'style': 'color:red;'}
  5. 错误处理(进阶)

    可加入 try-except 捕获文件读写异常,避免脚本中断。


五、总结

通过这两个脚本,你可以:

  • 快速为整个网站添加统一的顶部提示
  • 批量注入统计代码、客服浮窗、多语言切换按钮等
  • 自动化完成重复性 HTML 修改任务

Python + BeautifulSoup 是前端工程自动化的利器! 掌握它,让你从繁琐的手动操作中解放出来。


欢迎在评论区交流你的使用场景或遇到的问题!如果觉得有用,别忘了点赞 + 关注 👍

相关推荐
玄同7657 小时前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
小瑞瑞acd8 小时前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
火车叼位8 小时前
也许你不需要创建.venv, 此规范使python脚本自备依赖
python
火车叼位8 小时前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
孤狼warrior8 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Katecat996638 小时前
YOLO11分割算法实现甲状腺超声病灶自动检测与定位_DWR方法应用
python
玩大数据的龙威9 小时前
农经权二轮延包—各种地块示意图
python·arcgis
ZH15455891319 小时前
Flutter for OpenHarmony Python学习助手实战:数据库操作与管理的实现
python·学习·flutter
belldeep9 小时前
python:用 Flask 3 , mistune 2 和 mermaid.min.js 10.9 来实现 Markdown 中 mermaid 图表的渲染
javascript·python·flask
喵手9 小时前
Python爬虫实战:电商价格监控系统 - 从定时任务到历史趋势分析的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·电商价格监控系统·从定时任务到历史趋势分析·采集结果sqlite存储