Web scraping
How do I find elements by class in Beautiful Soup?
Pass class_ to find or find_all, or use select with a dot selector; both match a tag that has that class among others.
The two standard ways
In Beautiful Soup, soup.find_all("div", class_="price") returns every div whose class list includes price. The trailing underscore is there because class is a reserved word in Python. The CSS route, soup.select("div.price"), does the same with a CSS selector. Use find or select_one when you need only the first match.
from bs4 import BeautifulSoup # pip install beautifulsoup4
doc = BeautifulSoup(markup, "html.parser")
first_price = doc.find("span", class_="amount")
all_prices = doc.find_all("span", class_="amount")
same_via_css = doc.select("span.amount")
print(first_price.get_text(strip=True) if first_price else "none", len(all_prices))
Elements with several classes
HTML classes are a space separated list, and Beautiful Soup treats them that way. A tag with class="card card--sale featured" matches class_="card", class_="featured" and class_="card--sale" on their own. To require two classes at once, CSS is cleaner:
sale_cards = doc.select("div.card.featured") # both classes
not_sold = doc.select("div.card:not(.sold-out)") # one but not the other
Passing the full string class_="card featured" to find_all only matches when the attribute is exactly that text in that order, which is fragile. Prefer the CSS form for combinations.
Partial and changing class names
Modern front ends often generate class names such as ProductCard_price__x7Kq2, where the suffix changes with each release. Match the stable part instead:
- CSS attribute selector:
doc.select('[class*="ProductCard_price"]')matches any element whose class attribute contains that text. - Regular expression:
doc.find_all(class_=re.compile(r"^ProductCard_price"))tests each class in the list. - A function:
doc.find_all(class_=lambda c: c and c.startswith("price"))gives full control.
When classes are fully random, anchor on something steadier: an id, a data- attribute, an aria-label or nearby label text.
Reading text and attributes from the matches
Once you have the elements, .get_text(strip=True) returns clean text, and tag["href"] or tag.get("data-sku") reads attributes. Use .get() when an attribute may be missing, since square brackets raise KeyError.
Why a class search returns nothing
- The content is rendered by JavaScript. The class exists in the browser's DOM but not in the HTML your client downloaded. Search the raw response text for the class name to confirm, and see static or dynamic pages.
- You got a different page. A block page, a consent screen or a CAPTCHA challenge replaced the content. Print the page title to check. If it is a challenge, solve it before parsing, for example with a Cloudflare Challenge task for a full Cloudflare screen.
- Typos and case. Class matching is case sensitive.
Priceis notprice. - Searching the wrong tag name.
find_all("div", class_="x")misses aspanwith that class. Drop the tag name if unsure.
Keeping selectors maintainable
Put your selectors in one place, a dict or a small config file, rather than scattered through the code. When the site changes, you edit one line. Add a check that counts matches per page and alerts you when a selector that used to find twenty items finds none. Learn the wider toolkit in the guide to HTML parsing and the walkthrough on parsing HTML with Beautiful Soup.
Scoping searches to a container
Class names repeat across a page. A price class may appear in the main product, in a "related items" carousel and in the cart preview. Narrow the search by finding the container first and searching inside it: main = doc.select_one("section.product-detail"), then main.select(".price"). This avoids mixing values from different parts of the page, and it makes each selector shorter and easier to read.
Common questions
Why is it class_ and not class?
class is a reserved word in Python, so Beautiful Soup accepts class_ as the keyword argument instead.
Does class_ match when the tag has other classes too?
Yes. It matches if the given class appears anywhere in the tag's class list.
How do I match two classes at once?
Use select with both, such as div.card.featured, which requires both classes on the same tag.
Can I search by class without a tag name?
Yes. find_all(class_="price") or select(".price") match any tag type.
What if class names change on every deploy?
Match the stable prefix with a CSS contains selector or regex, or use ids and data attributes instead.
Keep reading
- Beautiful SoupThe forgiving Python library for parsing HTML and XML into a tree you can search by tag, attribute or CSS selector.
- CSS selectorCSS selectors are the compact pattern language for picking elements by tag, class, attribute and position, and most scraping tools speak it.
- How do I parse HTML with Beautiful Soup?Feed the page text to BeautifulSoup with a parser, then search the tree with select, find and get_text to pull fields.
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.