使用 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 是前端工程自动化的利器! 掌握它,让你从繁琐的手动操作中解放出来。


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

相关推荐
m0_7485548128 分钟前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
阿正呀2 小时前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
2501_901200532 小时前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
_.Switch2 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
Mr_sst2 小时前
Claude Code 部署与使用保姆级教程(2026 最新)
python·ai
瞎某某Blinder2 小时前
DFT学习记录[6]基于 HES06的能带计算+有效质量计算
python·学习·程序人生·数据挖掘·云计算·学习方法
m0_495496413 小时前
mysql处理复杂SQL性能_InnoDB优化器与MyISAM差异
jvm·数据库·python
forEverPlume4 小时前
PHP怎么使用Eloquent Attribute Composition属性组合_Laravel通过组合构建复杂属性【方法】
jvm·数据库·python
Aleeeeex4 小时前
RAG 那点事:从 8 份企业文档到能用的问答系统,全过程拆给你看
人工智能·python·ai编程