Open In App

How to delete child element in BeautifulSoup?

Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to delete child element. For this, various methods of the module is used.

Methods Used:



Approach:

Example 1:






# importing module
from bs4 import BeautifulSoup
  
markup = """
  
<!DOCTYPE>
<html>
  <head><title>Example</title></head>
  <body>
  <div id="parent">
    
<p>
    This is child of div with id = "parent".
    <span>Child of "P"</span>
  </p>
  
  <div>
  Another Child of div with id = "parent".
  </div>
  </div>
  
    
<p>
  Piyush
  </p>
  
                     
  </body>
</html>
"""
  
# parsering string to HTML
soup = BeautifulSoup(markup, 'html.parser')
  
# finding tag whose child to be deleted
div_bs4 = soup.find('div')
  
# delete the child element
div_bs4.clear()
  
print(div_bs4)

Output:

<div id="parent"></div>

Example 2:




# importing module
from bs4 import BeautifulSoup
  
markup = """
  
<!DOCTYPE>
<html>
  <head><title>Example</title></head>
  <body>
  <div id="parent">
    
<p>
    This is child of div with id = "parent".
    <span>Child of "P"</span>
  </p>
  
  <div>
  Another Child of div with id = "parent".
  </div>
  </div>
  
    
<p>
  Piyush
  </p>
  
                     
  </body>
</html>
"""
  
# parsering string to HTML
soup = BeautifulSoup(markup, 'html.parser')
  
# finding tag whose child to be deleted
div_bs4 = soup.find('div')
  
# delete the child element
div_bs4.decompose()
  
print(div_bs4)

Output:

<None></None>

Example 3:




# importing module
from bs4 import BeautifulSoup
  
markup = """
  
<!DOCTYPE>
<html>
  <head><title>Example</title></head>
  <body>
  <div id="parent">
    
<p>
    This is child of div with id = "parent".
    <span>Child of "P"</span>
  </p>
  
  <div>
  Another Child of div with id = "parent".
  </div>
  </div>
  
    
<p>
  Piyush
  </p>
  
                     
  </body>
</html>
"""
  
# parsering string to HTML
soup = BeautifulSoup(markup, 'html.parser')
  
# finding tag whose child to be deleted
div_bs4 = soup.find('div')
  
# delete the child element
div_bs4.replaceWith('')
  
print(div_bs4)

Output:

<div id="parent">
<p>
    This is child of div with id = "parent".
    <span>Child of "P"</span>
</p>
<div>
  Another Child of div with id = "parent".
  </div>
</div>

Article Tags :