Slashes and Brackets in Web Scraping with Python 2026: XPath vs CSS Explained Introduction to the Scrapy Selector in Python 2026 Setting up a Selector in Python 2026: Best Practices for Web Scraping Selecting Selectors in Python 2026: Best Practices for Web Scraping Extracting Data from a SelectorList in Python 2026: Best Practices CSS Locators in Python 2026: Powerful Web Scraping Techniques Attributes in CSS Selectors for Web Scraping in Python 2026 Selectors with CSS in Python 2026: Modern Web Scraping Techniques Text Extraction in Python 2026: Modern Techniques & Best Practices Crawl in Python 2026: Building Modern Web Crawlers with Best Practices A Classy Spider in Python 2026: Building Web Crawlers with Elegance & Best Practices Nodriver Canvas Fingerprint Spoofing 2026 – Advanced Anti-Detection Techniques WebGL Fingerprint Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion AudioContext Fingerprint Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion WebGL + AudioContext Integration Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion Canvas + WebGL Integration Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion Web Scraping with Python 2026 Web Scraping with Python in 2026 – Complete Beginner to Advanced Guide Python Web Scraping Tutorial 2026 – Playwright, Scrapy & BeautifulSoup Guide Building Your First Scrapy Spider in 2026 – Modern Python Web Scrapping Guide View all in this category →

CSS Locators in Python 2026: Powerful Web Scraping Techniques

Web Scraping Mar 24, 2026

CSS Locators in Python 2026: Powerful Web Scraping Techniques

CSS locators (also called CSS selectors) are one of the fastest and most readable ways to locate elements during web scraping. In 2026, with modern async scraping tools and dynamic websites, CSS locators remain the go-to choice for most Python developers due to their simplicity, speed, and maintainability compared to XPath.

This March 24, 2026 guide covers everything you need to know about using CSS locators effectively in Python web scraping with BeautifulSoup, parsel, httpx, and Playwright.

TL;DR — Key Takeaways 2026

  • CSS locators are faster and cleaner than XPath in most cases
  • Use .select() or .select_one() in BeautifulSoup
  • Master combinators, pseudo-classes, and attribute selectors
  • Combine with httpx + asyncio for high-performance crawlers
  • Prefer data attributes and specific selectors for stability

1. Basic CSS Locators


from bs4 import BeautifulSoup

html = """
<div class="product">
    <h2 class="title">MacBook Pro 2026</h2>
    <p class="price">$2499</p>
    <span class="rating" data-score="4.9">4.9 ★</span>
</div>
"""

soup = BeautifulSoup(html, "html.parser")

# By tag
titles = soup.select("h2")

# By class
prices = soup.select(".price")

# By ID
# soup.select("#main-product")

# By tag + class
products = soup.select("div.product")

print(titles[0].text)   # "MacBook Pro 2026"

2. Advanced CSS Locators in 2026


# Child combinator
soup.select("div.product > p.price")

# Descendant combinator
soup.select("div.product .rating")

# Adjacent sibling
soup.select("h2.title + p.price")

# Nth child
soup.select("li:nth-child(odd)")

# Attribute selectors
soup.select('a[href^="https"]')
soup.select('[data-testid="product-card"]')

# Pseudo-classes
soup.select("button:hover")
soup.select("tr:nth-of-type(2n)")

3. Real-World Async Scraping Example


import httpx
from bs4 import BeautifulSoup

async def scrape_page(url: str):
    async with httpx.AsyncClient(timeout=15.0) as client:
        response = await client.get(url)
        soup = BeautifulSoup(response.text, "html.parser")
        
        items = []
        for card in soup.select('div[data-product-card]'):
            item = {
                "title": card.select_one(".title").get_text(strip=True),
                "price": card.select_one(".price").get_text(strip=True),
                "rating": card.select_one(".rating").get_text(strip=True) if card.select_one(".rating") else None,
                "link": card.select_one("a")["href"] if card.select_one("a") else None
            }
            items.append(item)
        return items

# Usage: asyncio.run(scrape_page("https://example.com/products"))

4. Best Practices for CSS Locators in 2026

  • Be specific — avoid generic selectors like div or .item
  • Prefer data attributes — [data-testid="..."] is very stable
  • Use select_one() when expecting only one element
  • Handle missing elements gracefully with checks
  • Use Playwright when content is rendered by JavaScript
  • Document your locators — they will break less often

Building CSS Locators From Simple Parts

A CSS locator combines a few simple parts: a tag name, a class with a dot, an ID with a hash, and an attribute in square brackets. Combinators connect them: a space means descendant, > means direct child, and + means the element that directly follows.

Short locators are easier to read and survive layout changes better. Start from the nearest stable anchor, such as an ID or a data attribute, and move down only as far as needed.

Pseudo-classes such as :nth-of-type() and :not() are supported by BeautifulSoup through the soupsieve library and help with tables and lists.

Worked Example: Locators on a Small Table

We use descendant, child and :not() locators on a small table of results.

from bs4 import BeautifulSoup

soup = BeautifulSoup("""
<table id="results">
  <tr class="header"><th>Name</th><th>Score</th></tr>
  <tr><td>Ana</td><td>91</td></tr>
  <tr class="hidden"><td>Test</td><td>0</td></tr>
  <tr><td>Ben</td><td>78</td></tr>
</table>
""", "html.parser")

rows = soup.select("#results tr:not(.header):not(.hidden)")
print([[td.get_text() for td in r.select("td")] for r in rows])
print([td.get_text() for td in soup.select("#results tr > td:nth-of-type(2)")])

The first locator skips the header and hidden rows and returns Ana and Ben with their scores. The second returns every score column, including the hidden test row, which shows why the :not() filter matters.

Practical Tips

Test each locator in the browser's developer console with document.querySelectorAll before using it in Python. The count of matched elements tells you quickly whether the locator is too broad or too narrow.

Common Mistakes

  • Writing long paths copied from browser developer tools.
  • Confusing a space with > and matching nested elements by accident.
  • Forgetting that html.parser does not add tbody, while browsers show it.
  • Selecting hidden or template rows without filtering them.

Quick Summary

  • Tags, .class, #id and [attr] are the parts.
  • Space is descendant, > is child.
  • Start from a stable anchor.
  • :not() filters unwanted rows.

Conclusion — CSS Locators in 2026

CSS locators continue to be the most elegant and performant way to scrape data from websites in Python. In 2026, combining them with asynchronous requests and modern parsing libraries allows you to build fast, reliable, and maintainable scrapers. Focus on writing clean, specific selectors and always follow ethical scraping practices.

Next steps:

  • Practice writing specific CSS locators on real websites

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices