Last modified: Aug 19, 2023 By Alexander Williams

How to Find Parent Element in Beautifulsoup

You can use the .find_parent() method in Beautiful Soup to find the parent element of a tag.

This method returns a tag that is the present tag's closest ancestor that meets the given criteria.

What is the Parent element

In the context of HTML and XML documents, "parent element" refers to an element that contains one or more additional elements.

For example:

parent element

The picture you see is a parent div tag with a child <a> tag inside of it.

.find_parent() Syntax

This is the syntax of the .find_parent() method:

tag.find_parent()

How to use find_parent()

In the following example, we'll find the parent of the child <div> element.

from bs4 import BeautifulSoup

html = """
<div class="parent">
    <p>This is a paragraph.</p>
    <div class="child">
        <p>This is a child paragraph.</p>
    </div>
</div>
"""

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

# Find the parent of the child <div> element
child_div = soup.find('div', class_='child')
parent_div = child_div.find_parent('div', class_='parent')

print(parent_div)

Output:

<div class="parent">
<p>This is a paragraph.</p>
<div class="child">
<p>This is a child paragraph.</p>
</div>
</div>

This example uses the find_parent() method to find the parent <div> element with class "parent" of the specified child <div> element with class "child". 

It would display the complete parent <div> element with its contents.

If you want to get the text of the parent tag, visit Beautifulsoup: How to Get Text Inside Tag article.

Conclusion

Alright! You may now go through to locate parent items in Beautiful Soup. This understanding lets you efficiently navigate HTML and XML pages and find important elements. 

With the.find_parent() method, you can easily ascend the hierarchy of items, revealing tag relationships and improving web scraping and data extraction skills.