In this BeautifulSoup tutorial, we'll know how to find by CSS class.

syntax


soup.find_all(class_="class_name")

example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
html_source = '''
    <div>
       <p class="test1">hello world</p>
        <p class="test2"hello world</p>
         <p class="test3">hello world</p>
          <p class="test4">hello world</p>
    </div>   
'''

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

print(soup.find_all(class_="test1"))

output

1
[<p class="test1">hello world</p>] 


If you want to print just the value of tags, you need to follow this code bellow.


# print tag value
tags = soup.find_all(class_="test1")

for i in tags:
    print(i.string)

output

hello world


example 2: more accurately

in this example bellow we'll find all p tags that has "test1" as class

syntax

soup.find_all('tag_name', class_="class_name")

example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
html_source = '''
    <div>
       <p class="test1">hello world</p>
        <p class="test2"hello world</p>
         <p class="test3">hello world</p>
          <p class="test4">hello world</p>
    </div>   
'''

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

print(soup.find_all('p', class_="test1"))

output

1
[<p class="test1">hello world</p>]

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