gpt4 book ai didi

python - 使用Python和正则表达式,如何从html中删除标签?

转载 作者:行者123 更新时间:2023-11-30 23:22:22 27 4
gpt4 key购买 nike

使用python正则表达式,如何删除html中的所有标签?标签有时具有样式,如下所示:

<sup style="vertical-align:top;line-height:120%;font-size:7pt">(1)</sup>

我想删除一个较大的 html 字符串中的sup 标记之间的所有内容(包括sup 标记)。

最佳答案

我会使用 HTML 解析器 ( why )。例如,BeautifulSoupunwrap()可以照顾你的美丽的sup:

Tag.unwrap() is the opposite of wrap(). It replaces a tag with whatever’s inside that tag. It’s good for stripping out markup.

from bs4 import BeautifulSoup

data = """
<div>
<sup style="vertical-align:top;line-height:120%;font-size:7pt">(1)</sup>
</div>
"""

soup = BeautifulSoup(data)
for sup in soup.find_all('sup'):
sup.unwrap()

print soup.prettify()

打印:

<div>
(1)
</div>

关于python - 使用Python和正则表达式,如何从html中删除<sup>标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24533958/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com