How to find HTML element by class with BeautifulSoup?

To extract HTML elements with a specific class name using BeautifulSoup, we use the attrs parameter of the functions find or find_all.

For example, to extract ​​​​​the element that has mb-21 as a class name, we use the function find with attrs={"class": "mb-21"} like this:

import requests
from bs4 import BeautifulSoup

response = requests.get("https://www.scrapingbee.com/blog/")
soup = BeautifulSoup(response.content, 'html.parser')

h1 = soup.find(attrs={"class": "mb-21"})
print(h1.string)
# Output: The ScrapingBee Blog

 

Related BeautifulSoup web scraping questions: