Beautiful Soup - Functions Reference

Beautiful Soup Useful Resources

Beautiful Soup - find_parent() Method



Method Description

The find_parent() method in BeautifulSoup package finds the closest parent of this PageElement that matches the given criteria.

Syntax

find_parent( name, attrs, **kwargs)

Parameters

  • name − A filter on tag name.

  • attrs − A dictionary of filters on attribute values.

  • kwargs − A dictionary of filters on attribute values.

Return Type

The find_parent() method returns Tag object or a NavigableString object.

Example - Usage of find_parent() method

In the following example, we find the name of the tag that is parent to the string 'HR'.

from bs4 import BeautifulSoup

html = """
<html>
   <body>
      <h2>Departmentwise Employees</h2>
      <ul id="dept">
      <li>Accounts</li>
      <ul id='acc'>
      <li>Anand</li>
      <li>Mahesh</li>
      </ul>
      <li>HR</li>
      <ol id="HR">
      <li>Rani</li>
      <li>Ankita</li>
      </ol>
      </ul>
   </body>
</html>
"""

soup = BeautifulSoup(html, 'html.parser')

obj=soup.find(string='HR')
print (obj.find_parent().name)

Output

li

Example - Checking parent of body tag

The <body> tag is always enclosed within the top level <html> tag. In the following example, we confirm this fact with find_parent() method −

from bs4 import BeautifulSoup

html = """
<html>
   <body>
      <h2>Departmentwise Employees</h2>
      <ul id="dept">
      <li>Accounts</li>
      <ul id='acc'>
      <li>Anand</li>
      <li>Mahesh</li>
      </ul>
      <li>HR</li>
      <ol id="HR">
      <li>Rani</li>
      <li>Ankita</li>
      </ol>
      </ul>
   </body>
</html>
"""

soup = BeautifulSoup(html, 'html.parser')

obj=soup.find('body')
print (obj.find_parent().name)

Output

html
Advertisements