Find span tag python BeautifulSoup

in this tutorial, we'll learn how to find a Span tag or all Span tags using python BeautifulSoup.

1. Finding the Span tag (Syntax)

find H2 tag:


soup.span

find all Span tags:


soup.find_all('span')

2. Finding all the Span tags (Example)

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


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

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


#find span
print(soup.h2)

output:

  
<span>hello</span>  


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


from bs4 import BeautifulSoup
#html source
html_source = '''
<div  id="test">
     <h2> <span>hello</span>paragraph1</h2>
     <h2> <span>hello1</span>paragraph2</h2>
     <h2> <span>hello2</span>paragraph3</h2>
</div>
'''

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

#find all sppan
print(soup.find_all('span'))

output:


[<span>hello</span>, <span>hello1</span>, <span>hello2</span>]           

as you can see, we got all the sapn tags as a list.


happy coding!

English today is not an art to be mastered it's just a tool to use to get a result