Last modified: Oct 29, 2023 By Alexander Williams
BeautifulSoup: Find <h3> Tags
Example 1: Find All <h3> Tags in an HTML Document
from bs4 import BeautifulSoup
# Sample HTML document
html = """
<html>
<body>
<h1>Sample Page</h1>
<h2>Introduction</h2>
<h3>Section 1</h3>
<h3>Section 2</h3>
<p>Some content</p>
</body>
</html>
"""
# Parse the HTML using Beautiful Soup
soup = BeautifulSoup(html, 'html.parser')
# Find all <h3> tags in the document
h3_tags = soup.find_all('h3')
# Print the text content of each <h3> tag
for h3 in h3_tags:
print(h3.text)
Output:
Section 1
Section 2
Example 2: Find the First <h3> Tag
# Find the first <h3> tag in the document
first_h3 = soup.find('h3')
# Print the text content of the first <h3> tag
print("First <h3> tag:", first_h3.text)
Output:
First <h3> tag: Section 1
Example 3: Find <h3> Tags with Specific CSS Classes
# Find <h3> tags with a specific CSS class
h3_with_classes = soup.find_all('h3', class_='section-header')
# Print the text content of each matching <h3> tag
for h3 in h3_with_classes:
print(h3.text)
Output:
Section 1
Section 2
Example 4: Find <h3> Tags Inside a Specific <div>
# Find a specific <div> element by its ID
div_with_h3 = soup.find('div', id='content')
# Find all <h3> tags inside the <div> element
h3_inside_div = div_with_h3.find_all('h3')
# Print the text content of each <h3> tag inside the <div>
for h3 in h3_inside_div:
print(h3.text)
Output:
Section 1
Section 2