In BeautifulSoup, pass class_="your-class" to soup.find_all() / soup.find() (using a trailing underscore because class is a reserved Python keyword) or use CSS selector syntax with soup.select(".your-class"); in Selenium 4+, call driver.find_elements(By.CLASS_NAME, "your-class") for a single class token or driver.find_elements(By.CSS_SELECTOR, ".class-one.class-two") when matching multiple CSS classes together.
Basic Example
# 1. BeautifulSoup (static HTML parsing):
from bs4 import BeautifulSoup
html = """
<div class="card featured active">First Card</div>
<div class="card">Second Card</div>
<span class="badge">New</span>
"""
soup = BeautifulSoup(html, "html.parser")
# Recommended: `class_` matches any element containing that class token
cards = soup.find_all("div", class_="card")
print([c.get_text() for c in cards])
# Output: ['First Card', 'Second Card']
# CSS selector syntax (cleanest when chaining multiple classes or descendants):
featured = soup.select("div.card.featured")
print([el.get_text() for el in featured])
# Output: ['First Card']
# 2. Selenium 4+ (live browser / JavaScript-rendered DOM):
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("[https://example.com](https://example.com)")
# Single CSS class name (NO leading dot '.' in By.CLASS_NAME!):
single_match = driver.find_element(By.CLASS_NAME, "card")
all_cards = driver.find_elements(By.CLASS_NAME, "card")
# Multiple CSS classes together (use By.CSS_SELECTOR with dots):
featured_cards = driver.find_elements(By.CSS_SELECTOR, ".card.featured")
driver.quit()
Key Details & Edge Cases
- Multi-class elements (
class="card featured active") behave differently across APIs:- BeautifulSoup
class_="card": Splits the HTMLclassattribute into whitespace-separated tokens automatically, soclass_="card"matches<div class="card featured">even though"featured"is also present. To require multiple classes simultaneously, pass a list (soup.find_all(class_=["card", "featured"])) or usesoup.select(".card.featured"). - Selenium
By.CLASS_NAMErejects spaces: Passing compound class names likedriver.find_elements(By.CLASS_NAME, "card featured")raisesInvalidSelectorException: Compound class names not permittedin Selenium 4. Always switch toBy.CSS_SELECTORwith dot notation (".card.featured") whenever matching two or more classes.
- BeautifulSoup
- Never include a leading dot
.inclass_=orBy.CLASS_NAME:- Write
soup.find_all(class_="btn")anddriver.find_elements(By.CLASS_NAME, "btn")without a dot; include the leading dot only in CSS selector methods (soup.select(".btn")andBy.CSS_SELECTOR, ".btn").
- Write
- Deprecated Selenium 3 methods (
find_element__class_name):- Selenium 4 removed
driver.find_element__class_name(...)anddriver.find_elements__class_name(...)(which now raiseAttributeError). Always importfrom selenium.webdriver.common.by import Byand calldriver.find_element(By.CLASS_NAME, ...)ordriver.find_elements(By.CLASS_NAME, ...).
- Selenium 4 removed
- Single vs. multiple matches (
findvs.find_all,find_elementvs.find_elements):- In BeautifulSoup,
soup.find(class_="missing")returnsNonewhen nothing matches, whereassoup.find_all(...)/soup.select(...)return an empty list[]. - In Selenium,
driver.find_element(...)raisesNoSuchElementExceptionif not found (or if the JS element hasn’t rendered yet—useWebDriverWait+EC.presence_of_element_located), whereasdriver.find_elements(...)returns[]without raising.
- In BeautifulSoup,
- Exact full-attribute string match (rare edge case):
- If you only want elements whose
classattribute equals"card"and nothing else (excluding"card featured"), use an attribute dictionary:soup.find_all(attrs={"class": "card"})orBy.CSS_SELECTOR, '[class="card"]'.
- If you only want elements whose
Comparison of CSS Class Lookup Methods in BeautifulSoup vs. Selenium
| Library & Method | Leading . Required? |
Supports Multiple Classes (card + featured)? |
Return Value When Not Found | Best Used When |
|---|---|---|---|---|
BeautifulSoup: soup.find_all("tag", class_="name") (Recommended) |
No | Yes (class_=["a", "b"]) |
[] (None for .find()) |
Parsing static HTML when filtering by tag name + one or more CSS classes. |
BeautifulSoup: soup.select(".a.b") |
Yes | Yes (.a.b or .parent > .child) |
[] (None for .select_one()) |
Complex descendant, sibling, or multi-class CSS queries in static HTML. |
Selenium: driver.find_elements(By.CLASS_NAME, "name") |
No | No (raises InvalidSelectorException on spaces) |
[] (NoSuchElementException for find_element) |
Selecting elements by a single clean CSS class token in a live browser. |
Selenium: driver.find_elements(By.CSS_SELECTOR, ".a.b") (Recommended for multi-class) |
Yes | Yes (.a.b) |
[] (NoSuchElementException for find_element) |
Matching compound class names, attribute selectors, or nested DOM hierarchies in Selenium. |
You must log in or register to comment.
