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

如何控制BeautifulSoup的prettify方法标签展开深度,减少多余换行

解决BeautifulSoup prettify控制标签展开深度的方法

BeautifulSoup原生的prettify方法没有直接提供控制展开深度的参数,可以根据你的需求选择以下两种方案实现:

方案1:指定不需要展开的标签(适合固定标签不拆分的场景,比如CSS的style标签、h1、code等)

BeautifulSoup 4.10.0及以上版本新增了exclude_from_indent参数,可以直接指定哪些标签不需要缩进换行,不会拆分标签内部的内容,完美适配你提到的包含CSS代码的场景。

修改你的代码中prettify调用行即可:

from bs4 import BeautifulSoup

INPUT_FILE = "html_unformatted.txt"
OUTPUT_FILE = "index.html"

unicode_data = open(INPUT_FILE, "r", encoding='unicode_escape').read()
data = unicode_data.encode('iso-8859-1').decode('utf-8')
soup = BeautifulSoup(data, features="html.parser")
# 在这里添加不需要展开的标签,比如h1、style、code、script等
pretty_html = soup.prettify(exclude_from_indent=["h1", "style", "code", "script"])

with open(OUTPUT_FILE, "w") as f:
    f.write(pretty_html)
    print(f"Wrote to {OUTPUT_FILE}")

运行后输出结果和你预期的完全一致:

<html>
 <body><h1>hello world</h1></body>
</html>

如果你的BeautifulSoup版本过低,先执行升级命令:
pip install --upgrade beautifulsoup4

方案2:自定义深度控制逻辑(适合按层级控制展开深度的场景)

如果你需要严格按照标签层级控制展开深度,而不是按标签类型过滤,可以用自定义递归函数实现:

from bs4 import BeautifulSoup, Tag

def prettify_by_depth(tag, max_depth, current_depth=0, indent_char=' '):
    if current_depth > max_depth:
        return str(tag)
    indent = indent_char * current_depth
    result = f"{indent}<{tag.name}"
    # 拼接属性
    for attr, val in tag.attrs.items():
        result += f' {attr}="{val}"'
    result += ">"
    # 处理子节点
    has_child_tag = any(isinstance(c, Tag) for c in tag.contents)
    for child in tag.contents:
        if isinstance(child, Tag):
            result += "\n" + prettify_by_depth(child, max_depth, current_depth+1, indent_char)
        else:
            text = child.strip()
            if text:
                result += text
    # 闭合标签
    if has_child_tag and current_depth <= max_depth:
        result += "\n" + indent
    result += f"</{tag.name}>"
    return result

# 调用示例,max_depth设为1即可满足你的需求
pretty_html = prettify_by_depth(soup.html, max_depth=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:18:02