Beautiful Soup - 刪除子元素



HTML 文件是不同標籤的分層排列,其中一個標籤可能在多個層次上巢狀一個或多個標籤。我們如何刪除某個標籤的子元素?使用 BeautifulSoup,這很容易做到。

BeautifulSoup 庫中有兩種主要方法可以刪除某個標籤。decompose() 方法和 extract() 方法,區別在於後者返回被刪除的內容,而前者只是將其銷燬。

因此,要刪除子元素,請為給定的 Tag 物件呼叫 findChildren() 方法,然後對每個子元素呼叫 extract() 或 decompose()。

考慮以下程式碼段:

soup = BeautifulSoup(fp, "html.parser")
soup.decompose()
print (soup)

這將銷燬整個 soup 物件本身,它是文件的解析樹。顯然,我們不希望這樣做。

現在以下程式碼:

soup = BeautifulSoup(fp, "html.parser")
tags = soup.find_all()
for tag in tags:
   for t in tag.findChildren():
      t.extract() 

在文件樹中,<html> 是第一個標籤,所有其他標籤都是它的子元素,因此它將在迴圈的第一次迭代中刪除除 <html> 和 </html> 之外的所有標籤。

如果我們想刪除特定標籤的子元素,可以更有效地使用它。例如,您可能希望刪除 HTML 表格的標題行。

以下 HTML 指令碼有一個表格,第一個 <tr> 元素的標題由 <th> 標籤標記。

<html>
   <body>
      <h2>Beautiful Soup - Remove Child Elements</h2>
      <table border="1">
         <tr class='header'>
            <th>Name</th>
            <th>Age</th>
            <th>Marks</th>
         </tr>
         <tr>
            <td>Ravi</td>
            <td>23</td>
            <td>67</td>
         </tr>
         <tr>
            <td>Anil</td>
            <td>27</td>
            <td>84</td>
         </tr>
      </table>
   </body>
</html>

我們可以使用以下 Python 程式碼刪除 <th> 單元格具有 <tr> 標籤的所有子元素。

示例

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, "html.parser")
tags = soup.find_all('tr', {'class':'header'})

for tag in tags:
   for t in tag.findChildren():
      t.extract()

print (soup)

輸出

<html>
<body>
<h2>Beautiful Soup - Parse Table</h2>
<table border="1">
<tr class="header">

</tr>
<tr>
<td>Ravi</td>
<td>23</td>
<td>67</td>
</tr>
<tr>
<td>Anil</td>
<td>27</td>
<td>84</td>
</tr>
</table>
</body>
</html>

可以看出,<th> 元素已從解析樹中刪除。

廣告

© . All rights reserved.