您可以使用BeautifulSoup 完成此操作。您有两种选择,具体取决于您要对要删除的元素执行的操作。
设置:
from bs4 import BeautifulSoup
html_doc = """
<html>
<header>
<title>A test</title>
</header>
<body>
<table>
<tr>
<td id="MenuTD" style="vertical-align: top;">
Stuff here <a>with a link</a>
<p>Or paragraph tags</p>
<div>Or a DIV</div>
</td>
<td>Another TD element, without the MenuTD id</td>
</tr>
</table>
</body>
</html>
"""
soup = BeautifulSoup(html_doc)
- 选项 1 是使用
extract() 方法。使用它,您将保留提取元素的副本,以便稍后在应用程序中使用它:
代码:
menu_td = soup.find(id="MenuTD").extract()
此时,您要删除的元素已保存到menu_td 变量中。用它做你想做的事。 soup 变量中的 HTML 不再包含您的元素:
print(soup.prettify())
输出:
<html>
<header>
<title>
A test
</title>
</header>
<body>
<table>
<tr>
<td>
Another TD element, without the MenuTD id
</td>
</tr>
</table>
</body>
</html>
MenuTD 元素中的所有内容均已删除。你可以看到它仍然在 menu_td 变量中:
print(menu_td.prettify())
输出:
<td id="MenuTD" style="vertical-align: top;">
Stuff here
<a>
with a link
</a>
<p>
Or paragraph tags
</p>
<div>
Or a DIV
</div>
</td>
代码:
soup.find(id="MenuTD").decompose()
它不返回任何东西(不像.extract())。但是,它确实会从您的文档中删除该元素:
print(soup.prettify())
输出:
<html>
<header>
<title>
A test
</title>
</header>
<body>
<table>
<tr>
<td>
Another TD element, without the MenuTD id
</td>
</tr>
</table>
</body>
</html>