BeautifulSoup: .parent Example

Syntax

element.parent

.parent Example

from bs4 import BeautifulSoup

# Html source
html = """
<section>
<div>
<h2>Recent Posts:</h2>
</div>
</section>
"""

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

# Get h2 tag
h2 = soup.h2

# Print h2 parent
print(h2.parent)

Output:

<div>
<h2>Recent Posts:</h2>
</div>