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


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

相关推荐
老毛肚4 小时前
jeecg-boot-base-core 02 day
javascript·python
yaoxin5211234 小时前
434. Java 日期时间 API - Period 基于日期的时间段
java·开发语言·python
岁月宁静5 小时前
RAG 文档摄入全链路,从原理到生产落地
vue.js·人工智能·python
JaydenAI5 小时前
[对比学习LangChain和MAF-07]如何引入人机交互的审批流程
python·ai·langchain·c#·agent·hitl·maf
神奇元创6 小时前
商用级光路加速卡:大模型推理的极速落地方案
python·神经网络·fpga开发·dsp开发
运筹vivo@6 小时前
Python ContextVar 底层机制与内存模型拆解
前端·数据库·python
大白菜和MySQL6 小时前
java应用排查高线程
java·python
嵌入式协会20240726 小时前
(已解决)MinIO python 获取预签名出现forbidden、errornetwork等错误
java·开发语言·python
宸丶一7 小时前
Day 14:任务追踪 - 让 Agent 拥有项目管理能力
开发语言·python