”;
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 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>
In the following example, we find the name of the tag that is parent to the string ”HR”.
from bs4 import BeautifulSoup soup = BeautifulSoup(html, ''html.parser'') obj=soup.find(string=''HR'') print (obj.find_parent().name)
Output
li
Example 2
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 soup = BeautifulSoup(html, ''html.parser'') obj=soup.find(''body'') print (obj.find_parent().name)
Output
html
Advertisements
”;