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


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

相关推荐
AI探索者6 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者6 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh7 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅8 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽9 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时12 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿14 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python