How do you find HTML elements by CSS class name using BeautifulSoup or Selenium in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you find HTML elements by CSS class name using BeautifulSoup or Selenium in Python?

message-square
0

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 HTML class attribute into whitespace-separated tokens automatically, so class_="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 use soup.select(".card.featured").
    • Selenium By.CLASS_NAME rejects spaces: Passing compound class names like driver.find_elements(By.CLASS_NAME, "card featured") raises InvalidSelectorException: Compound class names not permitted in Selenium 4. Always switch to By.CSS_SELECTOR with dot notation (".card.featured") whenever matching two or more classes.
  • Never include a leading dot . in class_= or By.CLASS_NAME:
    • Write soup.find_all(class_="btn") and driver.find_elements(By.CLASS_NAME, "btn") without a dot; include the leading dot only in CSS selector methods (soup.select(".btn") and By.CSS_SELECTOR, ".btn").
  • Deprecated Selenium 3 methods (find_element_by_class_name):
    • Selenium 4 removed driver.find_element_by_class_name(...) and driver.find_elements_by_class_name(...) (which now raise AttributeError). Always import from selenium.webdriver.common.by import By and call driver.find_element(By.CLASS_NAME, ...) or driver.find_elements(By.CLASS_NAME, ...).
  • Single vs. multiple matches (find vs. find_all, find_element vs. find_elements):
    • In BeautifulSoup, soup.find(class_="missing") returns None when nothing matches, whereas soup.find_all(...) / soup.select(...) return an empty list [].
    • In Selenium, driver.find_element(...) raises NoSuchElementException if not found (or if the JS element hasn’t rendered yet—use WebDriverWait + EC.presence_of_element_located), whereas driver.find_elements(...) returns [] without raising.
  • Exact full-attribute string match (rare edge case):
    • If you only want elements whose class attribute equals "card" and nothing else (excluding "card featured"), use an attribute dictionary: soup.find_all(attrs={"class": "card"}) or By.CSS_SELECTOR, '[class="card"]'.

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.