Last modified: Jan 10, 2023 By Alexander Williams
How to Find any Elements by class in Beautifulsoup
In this Beautifulsoup tutorial, we'll learn 2 methods to find any elements by class name.
Method 1: Finding by class name
In the first method, we'll find all elements by Class name, but first, let's see the syntax.
syntax
soup.find_all(class_="class_name")
Now, let's write an example which finding all element that has test1 as Class name.
Example:
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')
# Find elements by 'test1' class
find_by_class = soup.find_all(class_="test1")
print(find_by_class)
output:
[<p class="test1">hello world</p>]
If you want to print the value of tags, you need to follow this code below.
# print tag value
tags = soup.find_all(class_="test1")
for i in tags:
print(i.string)
output
hello world
Method 2: Finding by class name & tag name
The second method is more accurate because we'll find elements by class name & tag name.
syntax
soup.find_all('tag_name', class_="class_name")
example:
In this example, we'll find all elements which have test1 in class name and p in Tag name.
html_source = '''
<div>
<p class="test1">hello world</p>
<p class="test2"hello world</p>
<h1 class="test1">hello world</h1>
<p class="test4">hello world</p>
</div>
'''
soup = BeautifulSoup(html_source, 'html.parser')
#
find_el = soup.find_all('p', class_="test1")
print(find_el)
If you look at the html_source, you'll see that has 2 elements that have test1 in class, but we'll get that have test1 in class and p in the tag name.
output:
[<p class="test1">hello world</p>]
happy coding!