Beautiful Soup - find_parents() Method



Method Description

The find_parent() method in BeautifulSoup package finds all parents of this Element that matches the given criteria.

Syntax

find_parents( name, attrs, limit, **kwargs)

Parameters

name − A filter on tag name.

attrs − A dictionary of filters on attribute values.

limit − Stop looking after specified number of occurrences have been found.

kwargs − A dictionary of filters on attribute values.

Return Type

The find_parents() method returns a ResultSet consisting of all the parent elements in a reverse order.

Example 1

We shall use following HTML script in this example −

<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>

Output

ul
body
html
[document]

Note that the name property of BeautifulSoup object always returns [document].

Example 2

In this example, the limit argument is passed to find_parents() method to restrict the parent search to two levels up.

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
obj=soup.find('li')
parents=obj.find_parents(limit=2)
for parent in parents:
   print (parent.name)

Output

ul
body
Advertisements