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


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

相关推荐
SeatuneWrite2 小时前
**AI漫剧软件2025推荐,解锁沉浸式二次元内容创作新体验
大数据·人工智能·python
Pyeako2 小时前
opencv计算机视觉--Harris角点检测&SIFT特征提取&图片抠图
人工智能·python·opencv·计算机视觉·harris角点检测·sift特征提取·图片抠图
艾莉丝努力练剑2 小时前
【AI时代的赋能与重构】当AI成为创作环境的一部分:机遇、挑战与应对路径
linux·c++·人工智能·python·ai·脉脉·ama
果粒蹬i2 小时前
从割裂到融合:MATLAB与Python混合编程实战指南
开发语言·汇编·python·matlab
木头左2 小时前
指数期权备兑策略的历史表现与Backtrader回测验证
python
yufuu982 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
qunaa01012 小时前
YOLOv26家具物品检测实战:基于Python和OpenCV实现家具识别系统
python·opencv·yolo
夕阳之后的黑夜2 小时前
Python脚本:为PDF批量添加水印
开发语言·python·pdf
2401_841495643 小时前
【LeetCode刷题】LRU缓存
数据结构·python·算法·leetcode·缓存·lru缓存·查找