How to Find HTML Element by Class with BeautifulSoup
You’ve opened your browser’s DevTools, identified the perfect CSS class that holds your target data, and fired up your Python editor. Now you’re staring at the BeautifulSoup documentation, wondering why soup.find('div', class='product-price') throws a syntax error. The red squiggly line mocks you. You’ve tried variations—class, className, cssClass—and nothing works. Meanwhile, the data you need sits right there in the HTML, seemingly unreachable.
Here’s the truth: you’re missing one character. Just one. And you’re not alone. This single stumbling block trips up nearly every BeautifulSoup beginner. I’ve watched developers with years of Python experience scratch their heads over this. The issue isn’t your logic—it’s that class is a reserved keyword in Python, and BeautifulSoup made a design choice that feels unintuitive until you understand why.
That’s where this guide comes in. I’m going to show you exactly how to find elements by class in BeautifulSoup, from the basic class_ syntax that solves your immediate problem to advanced techniques for handling multiple classes, partial matches, and complex filtering. Before diving deep, make sure you have BeautifulSoup properly set up by following this guide on how to install BeautifulSoup for web scraping. You’ll learn why BeautifulSoup works this way, when to use different approaches, and how to write class selectors that won’t break when websites update their markup. By the end, you’ll navigate class-based extraction with confidence—no more syntax errors, no more guessing, just clean, reliable code that works in 2026 and beyond.
Does BeautifulSoup Support Finding Elements by Class?
Yes, BeautifulSoup fully supports finding elements by class using the class_ keyword argument or the attrs dictionary. The class_ parameter (note the trailing underscore) is the standard approach, designed specifically to avoid Python’s reserved keyword conflict.
Here’s the basic syntax that works:
from bs4 import BeautifulSoup
html = """
<div class="product-card featured">
<h2 class="product-title">Wireless Headphones</h2>
<span class="price">$79.99</span>
</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Method 1: Using class_ (recommended)
title = soup.find('h2', class_='product-title')
print(title.text) # Output: Wireless Headphones
# Method 2: Using attrs dictionary
price = soup.find('span', attrs={'class': 'price'})
print(price.text) # Output: $79.99
Both methods return identical results. The class_ approach is more readable and Pythonic. The attrs dictionary shines when you need to match multiple attributes simultaneously.
The reason for the underscore? In Python, class is reserved for defining classes. BeautifulSoup chose class_ following Python’s convention of appending underscores to avoid keyword conflicts (similar to id_, type_, etc.). It’s a small price for consistency with the language.
Why Does soup.find(‘div’, class=’my-class’) Fail?
It fails because class is a reserved keyword in Python, making class='value' invalid syntax inside function arguments. Python’s parser sees class and expects a class definition, not a string value.
Here’s what happens when you try:
# This raises: SyntaxError: invalid syntax
# element = soup.find('div', class='my-class')
The error occurs at the Python level before BeautifulSoup even executes. Your code never runs. This confuses beginners because class works fine in HTML and CSS—just not as a keyword argument in Python.
The workaround is simple: add an underscore. BeautifulSoup recognizes class_ and internally maps it to the class attribute in the HTML:
# Correct syntax
element = soup.find('div', class_='my-class') # Works perfectly
Alternatively, use the attrs dictionary, which avoids the keyword issue entirely by passing class as a string key:
# Also correct - no underscore needed in dictionary keys
element = soup.find('div', attrs={'class': 'my-class'})
From my perspective, always use class_ for single-class lookups. It’s cleaner and signals to other developers that you understand BeautifulSoup conventions. For more details on the find() method’s capabilities, check out this comprehensive guide on how to use BeautifulSoup’s find() method.
How Do I Find Elements with Multiple Classes?
Pass a list of class names to class_ to match elements containing all specified classes. BeautifulSoup checks that every class in your list exists on the element, regardless of order.
Here’s how multi-class matching works:
from bs4 import BeautifulSoup
html = """
<div class="product-card featured sale">
<h2>Discount Headphones</h2>
</div>
<div class="product-card featured">
<h2>Regular Headphones</h2>
</div>
<div class="product-card">
<h2>Basic Headphones</h2>
</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Find elements with BOTH 'product-card' AND 'featured'
featured_products = soup.find_all('div', class_=['product-card', 'featured'])
for product in featured_products:
print(product.h2.text)
# Output:
# Discount Headphones
# Regular Headphones
Notice the first div has three classes (product-card featured sale), but it still matches because it contains both required classes. The third div, with only product-card, is excluded.
For even more precision, combine with other attributes:
# Must have both classes AND specific data attribute
specific = soup.find('div', class_=['product-card', 'sale'],
attrs={'data-currency': 'USD'})
This pattern—class list + attribute filtering—handles complex modern websites where single-class selection returns too many matches. When you need to extract multiple elements at once, learn more about how to use BeautifulSoup’s find_all() method for efficient batch processing.
How Do I Find Elements by Partial Class Name?
Use CSS selectors with the [class*="substring"] syntax or regular expressions with the attrs parameter. BeautifulSoup’s basic class_ parameter requires exact matches (for single classes) or full inclusion (for lists).
Method 1: CSS Selectors for Substring Matching
from bs4 import BeautifulSoup
html = """
<div class="col-md-6 col-sm-12">Content 1</div>
<div class="col-lg-4 col-md-8">Content 2</div>
<div class="col-xs-12">Content 3</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Find all elements with class containing 'col-md'
cols = soup.select('[class*="col-md"]')
for col in cols:
print(col.text)
# Output:
# Content 1
# Content 2
The *= operator is a CSS attribute substring selector. It matches anywhere in the class string, not just at the beginning.
Method 2: Regular Expressions
import re
# Find classes starting with 'col-'
cols = soup.find_all('div', attrs={'class': re.compile(r'^col-')})
# Find classes containing 'md' anywhere
cols = soup.find_all('div', attrs={'class': re.compile(r'col-md')})
Regular expressions offer maximum flexibility—anchors (^, $), alternation (|), character classes. But honestly? CSS selectors are more readable for simple patterns. Save regex for complex logic.
How Do I Use CSS Selectors to Find by Class?
Use soup.select() or soup.select_one() with standard CSS syntax—dot notation for classes, combinations for precision. CSS selectors often prove more concise than find() for complex queries.
Here’s the CSS selector approach:
from bs4 import BeautifulSoup
html = """
<nav class="main-nav">
<ul class="menu">
<li class="item active"><a href="/">Home</a></li>
<li class="item"><a href="/shop">Shop</a></li>
<li class="item"><a href="/about">About</a></li>
</ul>
</nav>
"""
soup = BeautifulSoup(html, 'lxml')
# Basic class selection - same as find()
home_link = soup.select_one('.item.active a')
print(home_link['href']) # Output: /
# Descendant selection
nav_items = soup.select('nav.main-nav ul.menu li.item')
print(len(nav_items)) # Output: 3
# Direct child selection
menu_items = soup.select('ul.menu > li.item')
CSS selectors shine for hierarchical navigation. The space character selects descendants; > selects direct children. You can chain classes (.item.active), combine with IDs (#header.nav-fixed), and use pseudo-classes (:first-child, :nth-of-type).
Comparison: find() vs select() for class-based extraction:
| Task | find() Method | select() Method |
|---|---|---|
| Single class | soup.find(class_='item') | soup.select_one('.item') |
| Multiple classes | soup.find(class_=['item', 'active']) | soup.select_one('.item.active') |
| Class + tag | soup.find('li', class_='item') | soup.select_one('li.item') |
| Descendant with class | Chain multiple find() calls | soup.select('.menu .item') |
| Partial class match | Requires regex | soup.select('[class*="col"]') |
I use find() when I need to manipulate the tree afterward (it returns a Tag object with all BeautifulSoup methods). I use select() for quick, readable extraction, especially with complex selectors. For situations where CSS selectors aren’t powerful enough, you might wonder can I use XPath selectors in BeautifulSoup—the answer involves integrating with lxml for advanced navigation.
How Do I Handle Dynamic or Changing Class Names?
Target stable parent elements, use partial class matching, or combine multiple attributes to create robust selectors. Websites change class names frequently—often during redesigns or A/B testing.
Strategy 1: Target Parent Containers
# Instead of targeting the volatile inner class
# price = soup.find('span', class_='price-2x3j9') # Changes daily!
# Target the stable parent + relative navigation
product = soup.find('div', class_='product-card')
price = product.find('span', class_=re.compile(r'^price-')) # Partial match
Strategy 2: Use Data Attributes
# Data attributes change less frequently than styling classes
product = soup.find('div', attrs={'data-product-id': '12345'})
price = product.find('span', attrs={'data-price': True}) # Any value
Strategy 3: Text Content Matching
# Find by text when classes are random
import re
add_button = soup.find('button', text=re.compile(r'add to cart', re.I))
From experience, the most stable selectors combine element hierarchy with semantic attributes. Avoid classes that look generated (random strings, hash suffixes). Look for data-* attributes, IDs, or semantic class names like product, article, navigation. Building resilient scrapers requires understanding broader web scraping best practices that go beyond just class selection.
How Do I Find All Elements with a Specific Class?
Use find_all() instead of find() to return a list of all matching elements. This is essential for scraping lists, grids, or tables.
from bs4 import BeautifulSoup
html = """
<div class="product-grid">
<div class="product">
<h3>Product A</h3>
<span class="price">$10</span>
</div>
<div class="product">
<h3>Product B</h3>
<span class="price">$20</span>
</div>
<div class="product">
<h3>Product C</h3>
<span class="price">$30</span>
</div>
</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Find all products
products = soup.find_all('div', class_='product')
print(f"Found {len(products)} products") # Output: Found 3 products
# Process each one
data = []
for product in products:
name = product.find('h3').text
price = product.find('span', class_='price').text
data.append({'name': name, 'price': price})
print(data)
# Output: [{'name': 'Product A', 'price': '$10'}, ...]
find_all() accepts the same parameters as find()—tag name, class_, attrs, etc. It returns a ResultSet (essentially a list) that you can iterate, slice, or index.
Performance tip: If you only need the first few matches, use the limit parameter:
# Stop after finding 5 products (faster on large pages)
first_five = soup.find_all('div', class_='product', limit=5)
How Do I Exclude Elements with Certain Classes?
Use CSS selectors with the :not() pseudo-class or filter results with list comprehension. BeautifulSoup doesn’t have a direct “exclude class” parameter, but CSS selectors handle this elegantly.
Method 1: CSS :not() Selector
from bs4 import BeautifulSoup
html = """
<div class="product">Regular Product</div>
<div class="product sponsored">Sponsored Product</div>
<div class="product">Another Regular</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Find products WITHOUT 'sponsored' class
regular = soup.select('div.product:not(.sponsored)')
for item in regular:
print(item.text)
# Output:
# Regular Product
# Another Regular
Method 2: List Comprehension Filtering
# Find all products, then filter
all_products = soup.find_all('div', class_='product')
regular_products = [p for p in all_products if 'sponsored' not in p.get('class', [])]
# More complex: exclude multiple classes
excluded = ['sponsored', 'out-of-stock']
filtered = [p for p in all_products if not any(c in p.get('class', []) for c in excluded)]
The CSS approach is cleaner for simple exclusions. Python filtering offers more complex logic—checking multiple attributes, text content, or nested elements.
How Do I Find Elements with Exact Class Matching?
Use a custom function or regular expressions to ensure no extra classes exist. By default, class_=['class-a', 'class-b'] matches elements with at least those classes, potentially plus others.
For exact matching (only these classes, no more):
from bs4 import BeautifulSoup
html = """
<div class="btn primary">Button 1</div>
<div class="btn primary large">Button 2</div>
<div class="btn secondary">Button 3</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Custom function for exact class matching
def exact_class_match(tag, classes):
tag_classes = tag.get('class', [])
return set(tag_classes) == set(classes)
# Find only elements with EXACTLY 'btn' and 'primary'
exact_buttons = soup.find_all(lambda tag: exact_class_match(tag, ['btn', 'primary']))
for btn in exact_buttons:
print(btn.text) # Output: Button 1 only (Button 2 has extra 'large')
This is rarely needed in practice—usually you want “at least these classes.” But for strict validation or testing, exact matching ensures predictable results.
How Do I Handle Class Names with Special Characters?
Use the attrs dictionary or CSS selectors with proper escaping. Class names with spaces, colons, or other special characters require careful handling.
from bs4 import BeautifulSoup
html = """
<div class="item:featured">Special Syntax</div>
<div class="col-xs-12 col-sm-6">Bootstrap Grid</div>
"""
soup = BeautifulSoup(html, 'lxml')
# Method 1: attrs dictionary (handles anything)
special = soup.find('div', attrs={'class': 'item:featured'})
# Method 2: CSS selector with escaping (for CSS special chars)
# Note: colons in CSS need escaping with backslash
bootstrap = soup.select_one(r'div.col-xs-12\.col-sm-6') # Raw string for backslash
Honestly, class names with colons, spaces, or unicode are poor practice, but you inherit them from frameworks like Bootstrap or Tailwind. The attrs dictionary is your safest bet for weird characters.
FAQ: Finding Elements by Class in BeautifulSoup
Can I use class without the underscore in any situation?
No, never in keyword arguments. The underscore is mandatory for class_ in find(), find_all(), and similar methods. The only exception is the attrs dictionary, where class is a string key, not a Python keyword.
Why does class_='my-class' return None when the class exists?
Usually because the element has multiple classes and you’re matching against the combined string. Check the actual HTML—if the class is class="my-class active", searching for exactly my-class with attrs={'class': 'my-class'} fails. Use class_='my-class' (which handles lists) or class_=['my-class'].
Is find() case-sensitive for class names?
Yes, HTML class names are case-sensitive, and BeautifulSoup respects this. class_='Product' won’t match class="product". Use regular expressions with the re.I flag for case-insensitive matching:
import re
element = soup.find('div', class_=re.compile(r'product', re.I))
Can I find elements by class using the element’s .get() method?
Yes, but it’s manual and inefficient. You’d iterate all elements checking element.get('class'), which is what find_all() does internally. Always use built-in methods—they’re optimized in C.
Does BeautifulSoup support class name ordering in matches?
No, order doesn’t matter. class_=['a', 'b'] matches class="b a" or class="a b" identically. HTML class order has no semantic meaning.
Can I use select() with multiple classes in any order?
Yes, .class1.class2 matches regardless of order in the HTML. soup.select('.a.b') finds <div class="b a"> just fine.
How do I debug why my class selector returns nothing?
Print the element’s actual classes:
element = soup.find('div')
print(element.get('class')) # See the list of classes
print(element['class']) # Alternative syntax
Common issues: typos, extra whitespace, unexpected additional classes, or dynamic JavaScript-added classes not in the initial HTML. If you’re still stuck, review these common errors in Python that often trip up web scrapers, including syntax mistakes that prevent your code from running properly.
Is there a performance difference between find() and select() for class matching?
Negligible for most use cases. find() with class_ is slightly faster as it’s more direct. select() parses CSS syntax which adds minimal overhead. For high-volume scraping (10,000+ elements), benchmark both, but readability usually matters more than microseconds.
Conclusion: Master Class-Based Selection in BeautifulSoup
You’ve learned every approach to finding elements by class in BeautifulSoup—from the essential class_ parameter to advanced CSS selectors, partial matching, and defensive strategies for changing websites. You now understand why that underscore exists, when to use find() versus select(), and how to build robust selectors that survive site updates.
The key points to remember:
- Always use
class_(with underscore) for the cleanest, most Pythonic code - Use
attrs={'class': 'name'}when you need to avoid the underscore or combine with other attributes - Choose
select()for complex hierarchies andfind()for simple lookups or tree manipulation - Combine strategies—parent elements, data attributes, partial matching—to handle dynamic class names
- Check for None before accessing text or attributes to prevent crashes
Now it’s your turn. Open your target website, inspect the class structure, and write your first robust selector. Start with find('tag', class_='name'), expand to find_all() for lists, and add CSS selectors when navigation gets complex. Test your code against multiple pages to ensure consistency.
As you build your scraping skills, remember that technical ability must pair with responsibility. Before scraping any website, familiarize yourself with robots.txt for web scraping to understand site permissions, and review how to scrape data from websites legally to ensure your projects remain compliant with regulations and terms of service. For deeper scraping knowledge, explore finding elements by ID or learn about handling dynamic content when static class selection isn’t enough. If you’re building larger projects, consider web scraping best practices to structure your code for maintainability.
