删除保留python样式的html(标记)部分

2024-04-25 22:33:34 发布

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

我想删除一个html的一部分,其中包含一个特定的字符串,然后再保存它。标签包含一个人的名字,我想删除整个标签,使其匿名。你知道吗

html是:

<div id="top-card" data-li-template="top_card">...</div>

以及所有的孩子。你知道吗

我尝试使用beautifulsoup,但找不到解决方案。你知道吗

有没有一种方法可以在保持样式完整的同时删除整个html的“部分”?你知道吗

谢谢!你知道吗


Tags: 方法字符串dividdatatophtml孩子
1条回答
网友
1楼 · 发布于 2024-04-25 22:33:34

可以使用^{}BeautifulSoup中删除元素。你知道吗

假设要删除id为“top card”的div:

>>> html = """
... <div id="top-card" data-li-template="top_card"><div>test</div></div>
... <div>test</div> <div id="foo">blah</div>"""
>>> soup = BeautifulSoup(html)
>>> [div.extract() for div in soup("div",id="top-card")]
[<div data-li-template="top_card" id="top-card"><div>test</div></div>]
>>> soup
<html><body>
<div>test</div> <div id="foo">blah</div></body></html>

相关问题 更多 >