[英]Python: How do you remove a tag in a tag?
我想刪除 h4 標簽,保持 li 完好無損我正在使用 BeautifulSoup
在 index.html 中
<li id="myID">
<h4 class="ipsType_minorHeading">Ilość treści</h4>
666
</li>
我想得到
<li id="myID">666</li>
我的代碼
...
html_file = open("index.html").read()
index_file = BeautifulSoup(html_file, 'lxml')
使用 CSS select
找到您想要的節點,然后decompose
它們。 我使用了這個類,因為它看起來很重要,但你可以使用h4
、標簽本身、 li h4
(不是很正常的 html,順便說一句)或任何提供你需要的選擇性的 CSS。
html = """<li id="myID">
<h4 class="ipsType_minorHeading">Ilość treści</h4>
666
</li>"""
from bs4 import BeautifulSoup as bs
soup = bs(html)
for hit in soup.select(".ipsType_minorHeading"):
hit.decompose()
print(soup.prettify())
請注意,當給定一段 html 時,BeautifulSoup 往往會添加 html 和 body 標簽。
<html>
<body>
<li id="myID">
666
</li>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.