2 Ways to Find by Multiple Class in Beautifulsoup

2 Ways to Find by Multiple Class in Beautifulsoup

To find multiple classes in Beautifulsoup, we will use:

  • find_all() function
  • select() function

In this tutorial, we'll learn how to use find_all() or select() to find elements by multiple classes.

find_all() to find by Multiple Class

In the following example, we'll find all tags with 'p_1', 'p_2', or 'p_3' in the class.

from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module

# 👇 HTML Source
my_html = '''
<p class="p_1">Hello P1</p>
<p class="p_2">Hello P2</p>
<p class="p_3">Hello P3</p>
'''

soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing

els = soup.find_all(class_=['p_1', 'p_2', 'p_3']) # 👉️ Find all By Multiple Class

print(els)

Output:

[<p class="p_1">Hello P1</p>, <p class="p_2">Hello P2</p>, <p class="p_3">Hello P3</p>]

We can also use attrs instead of class_ parameter as in the following example.

from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module

# 👇 HTML Source
my_html = '''
<p class="p_1">Hello P1</p>
<p class="p_2">Hello P2</p>
<p class="p_3">Hello P3</p>
'''

soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing

els = soup.find_all(attrs={'class':['p_1', 'p_2', 'p_3']}) # 👉️ Find all with Multiple Class using attrs

print(els)

Output:

[<p class="p_1">Hello P1</p>, <p class="p_2">Hello P2</p>, <p class="p_3">Hello P3</p>]

See the example below if you want to add the tag to your filtring.

from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module

# 👇 HTML Source
my_html = '''
<p class="p_1">Hello P1</p>
<p class="p_2">Hello P2</p>
<p class="p_3">Hello P3</p>
'''

soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing

els = soup.find_all("p", class_=['p_1', 'p_2', 'p_3']) # 👉️ Find all <p> with Multiple Class

print(els)

Output:

[<p class="p_1">Hello P1</p>, <p class="p_2">Hello P2</p>, <p class="p_3">Hello P3</p>]

Select() to find by Multiple Class

Using select() is another way to find by multiple classes. Let's see how it works.

from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module

# 👇 HTML Source
my_html = '''
<p class="p_1">Hello P1</p>
<p class="p_2">Hello P2</p>
<p class="p_3">Hello P3</p>
'''

soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing

els = soup.select(".p_1, .p_2, .p_3") # 👉️ Find all by Multiple Class using Select

print(els)

Output:

[<p class="p_1">Hello P1</p>, <p class="p_2">Hello P2</p>, <p class="p_3">Hello P3</p>]

As you can see, we've used CSS syntax to select by multiple.