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

如何使用Regex移除空标签并合并同名相邻标签?

移除空标签并合并相邻同名标签的解决方案

这里用Python的BeautifulSoup库来实现需求,步骤如下:

1. 安装依赖

如果还没安装BeautifulSoup和lxml解析器,先执行:

pip install beautifulsoup4 lxml

2. 实现代码

from bs4 import BeautifulSoup, Tag

def clean_and_merge_html(html_content):
    soup = BeautifulSoup(html_content, 'lxml')
    
    # 移除空标签(无文本、无子标签的标签)
    for tag in soup.find_all():
        if not tag.get_text(strip=True) and not tag.contents:
            tag.decompose()
    
    # 合并相邻的同名标签
    tags = list(soup.find_all())
    i = 0
    while i < len(tags) - 1:
        current_tag = tags[i]
        next_tag = tags[i+1]
        
        # 检查是否是相邻同名标签,且属于同一父节点
        if (current_tag.name == next_tag.name 
            and current_tag.parent == next_tag.parent):
            # 将下一个标签的内容移到当前标签
            current_tag.extend(next_tag.contents)
            # 移除下一个标签
            next_tag.decompose()
            # 更新标签列表(因为移除了元素,长度变化)
            tags = list(soup.find_all())
            # 不递增i,继续检查当前标签的新下一个兄弟
            continue
        i += 1
    
    return str(soup)

# 测试示例1
test_html1 = "<i>12341234</i><b></b>"
print(clean_and_merge_html(test_html1))
# 输出: <i>12341234</i>

# 测试示例2
test_html2 = "<b>1234</b><b>5678</b>"
print(clean_and_merge_html(test_html2))
# 输出: <b>12345678</b>

代码说明

  • 移除空标签:遍历所有标签,判断标签是否既无有效文本(get_text(strip=True)为空)又无子标签,满足则删除该标签。
  • 合并相邻同名标签:遍历标签列表,检查当前标签与下一个标签是否同名且同属一个父节点,若是则将下一个标签的内容合并到当前标签,再删除下一个标签,之后重新生成标签列表继续检查(避免索引混乱)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:55:24