簡體   English   中英

Python:如何刪除標簽中的標簽?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM