Last modified: Jan 10, 2023 By Alexander Williams

Find H2 tag by using python BeautifulSoup

In this tutorial, we'll learn how to find the h2 tag by using python BeautifulSoup.

1. Finding the H2 tag (Syntax)

find H2 tag:


soup.h2

find all H2 tags:


soup.find_all('h2')

2. Finding all h2 tags (Example)

In the first example, we'll find the H2 element.


from bs4 import BeautifulSoup
#html source
html_source = '''
<div id="test">
     <h2>paragraph1</h2>
</div>
'''

soup = BeautifulSoup(html_source, 'html.parser')
#find h2 tag
print(soup.h2)

output:


<h2>paragraph1</h2> 


in the second example, we'll find all the H2 tags.


from bs4 import BeautifulSoup
#html source
html_source = '''
<div id="test">
     <h2>paragraph1</h2>
  </div>

  <div id="test">
     <h2>paragraph2</h2>
  </div>

  <div id="test">
     <h2>paragraph3</h2>
  </div>

  <div id="test">
     <h2>paragraph4</h2>
  </div> 

  <div id="test">
     <h2>paragraph5</h2>
  </div>

  <div id="test">
     <h2>paragraph6</h2>
  </div>
'''

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



#find all 'h2' tags
find_all = soup.find_all('h2')
print(find_all)   

output:


[<h2>paragraph1</h2>, <h2>paragraph2</h2>, <h2>paragraph3</h2>, <h2>paragraph4</h2>, <h2>paragraph5</h2>, <h2>paragraph6</h2>]        

as you can see, we got all h2 tags as a list


happy coding!