You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现每个<div>元素后插入换行符

Python实现给HTML文档中每个
元素后插入换行符

根据需求,这里提供三种不同场景下的实现方案,你可以根据HTML文档的复杂度选择:

1. 简单字符串替换(适合无属性的
标签)

如果你的HTML里的

都是不带属性的基础标签,直接用字符串替换最快捷:

with open("input.html", "r", encoding="utf-8") as f:
    content = f.read()

# 将所有"<div>"替换为"<div>\n"
modified_content = content.replace("<div>", "<div>\n")

with open("output.html", "w", encoding="utf-8") as f:
    f.write(modified_content)

2. 正则表达式替换(支持带属性的
标签)

如果需要匹配带属性的<div class="xxx">这类标签,用正则可以覆盖所有

开头的标签:

import re

with open("input.html", "r", encoding="utf-8") as f:
    content = f.read()

# 匹配所有<div开头的标签,捕获后添加换行符
modified_content = re.sub(r"(<div[^>]*>)", r"\1\n", content)

with open("output.html", "w", encoding="utf-8") as f:
    f.write(modified_content)

注意:正则可能会误匹配HTML注释或文本内容里的<div>字符串,适合结构相对规范但带属性的文档。

3. 用BeautifulSoup解析(最可靠,复杂HTML首选)

如果HTML文档结构复杂(嵌套标签、注释、脚本内容等),用专业的HTML解析库能避免误操作:

from bs4 import BeautifulSoup

with open("input.html", "r", encoding="utf-8") as f:
    soup = BeautifulSoup(f.read(), "html.parser")

# 遍历所有div元素,在每个元素后插入换行符
for div in soup.find_all("div"):
    div.insert_after("\n")

# 保存修改后的文档
with open("output.html", "w", encoding="utf-8") as f:
    f.write(str(soup))

这种方法会严格按照HTML DOM结构操作,不会影响注释或文本中的<div>字符,是处理复杂HTML的最优解。

内容的提问来源于stack exchange,提问作者PJ Laube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:55:22