标记中的Python调试HTML标记

2024-09-27 00:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用streamlight高亮显示文本中的不同关键字,因此我用 <span style="background-color: #XXXXXX"> keyword </span>但由于某些关键字是短语,我在类似<span>的文本中以<span>结尾

<span style="background-color:FFFF000"> The quick brown fox <span style..>jumps</span> over the lazy dog </span>

这将导致解析此字符串中的标记或HTML时出错:

我正在考虑定义一个函数来传递字符串,并在任何情况下删除内部跨度

def html_debugger(text):
    magic
    return text

它将返回<span style="background-color:FFFF000"> The quick brown fox jumps over the lazy dog </span> 但我不知道该如何思考这个函数


Tags: the文本style关键字quicklazycolorover
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:43

有两种方法

首先,对于标准库re,它应该可以处理任何类型的标记,而不仅仅是span

import re

html = """<span style="background-color:FFFF000"> The quick brown fox <span style="test">jumps</span> over the lazy dog </span>"""

def html_debugger(text):
    tag_pattern = r'<[^>]*>'
    tags = re.findall(tag_pattern, text)
    inside_text = re.sub(tag_pattern, '', text)
    
    return tags[0] + inside_text + tags[-1]

html_debugger(html)
# '<span style="background-color:FFFF000"> The quick brown fox jumps over the lazy dog </span>'

第二个是BeautifulSoup

from bs4 import BeautifulSoup

html = """<span style="background-color:FFFF000"> The quick brown fox <span style="test">jumps</span> over the lazy dog </span>"""

def html_debugger(text):
    bs_span = BeautifulSoup(text)
    span = s.find_all('span')[0]
    
    span_text = span.text
    span_style = span.attrs['style']
    
    return f'<span style="{span_style}">{span_text}</span>'

html_debugger(html)
# '<span style="background-color:FFFF000"> The quick brown fox jumps over the lazy dog </span>'

相关问题 更多 >

    热门问题