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

如何用Python修复字符串中格式错误的HTML标签?

解决方案

1. 正则表达式精准修复错误标签

直接通过正则匹配并清除HTML标签内的多余空格,完全保留原文本的排版结构:

import re

def fix_broken_html_tags(html_content):
    # 修复闭合标签(如</h 3 > → </h3>)
    html_content = re.sub(r'</\s*(\w+)\s*>', r'</\1>', html_content)
    # 修复起始标签(如<h 1 > → <h1>,同时保留属性)
    html_content = re.sub(r'<\s*(\w+)(\s[^>]*?)?\s*>', r'<\1\2>', html_content)
    return html_content

# 示例调用
broken_html = "示例内容</h 3 >,包含错误的</ strong>标签"
fixed_html = fix_broken_html_tags(broken_html)

2. 手动遍历字符修复(复杂场景适配)

如果遇到更复杂的标签格式错误,可通过逐字符遍历的方式精准处理标签区间,完全控制修复逻辑:

def fix_html_tags_manual(html_content):
    fixed = []
    in_tag = False
    current_tag = []
    for char in html_content:
        if char == '<':
            in_tag = True
            current_tag = ['<']
        elif char == '>' and in_tag:
            in_tag = False
            tag_str = ''.join(current_tag[1:])
            if tag_str.startswith('/'):
                # 处理闭合标签
                tag_name = tag_str[1:].strip()
                fixed.append(f'</{tag_name}>')
            else:
                # 处理带属性的起始标签
                parts = tag_str.split(maxsplit=1)
                tag_name = parts[0].strip()
                attrs = parts[1] if len(parts) > 1 else ''
                fixed.append(f'<{tag_name}{attrs}>')
        elif in_tag:
            current_tag.append(char)
        else:
            fixed.append(char)
    return ''.join(fixed)

# 示例调用
broken_html = "<h 1 class='title'>错误标题</h 1 >"
fixed_html = fix_html_tags_manual(broken_html)

3. 使用lxml修复(兼顾严谨性与结构保留)

若需要更严谨的HTML语法修复,同时想保留原文本的换行和空白结构,可使用lxml并设置对应参数:

from lxml import html

def fix_html_with_lxml(html_content):
    parser = html.HTMLParser(remove_blank_text=False, preserve_blank_lines=True)
    tree = html.fromstring(html_content, parser=parser)
    fixed_html = html.tostring(tree, encoding='unicode', method='html')
    return fixed_html

# 示例调用
broken_html = "第一段落\n<h 2>错误标题</h 2 >\n第二段落"
fixed_html = fix_html_with_lxml(broken_html)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:40:06