In Python, a CSS selector is a pattern you pass to a parsing library to find elements in an HTML tree. For example, Beautiful Soup can find every product title with soup.select(".product-title"), or just the first with soup.select_one(".product-title"). The selector does not fetch a page, run its JavaScript, or create the tree: your code must first obtain and parse HTML that contains the elements you want.
What CSS selectors do in Python
A CSS selector describes which HTML elements to match. Selectors are also used in CSS rules to target elements for styling, but in Python they are commonly used as a concise way to search a parsed document. A parser turns markup into a tree; a selector searches that tree. Those are separate jobs.
For instance, article a[href] means “find links with an href somewhere inside an article.” It does not mean “open a browser and find whatever a person would see on the page.” If a page builds its content with JavaScript, the original HTML response may not contain the target element. A parser cannot select a node that is absent from its input.
Common selector syntax
These patterns cover many everyday searches. A library’s selector engine determines which syntax it supports, so treat the examples as common CSS forms rather than a promise that every Python package implements every CSS feature.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
| Goal | Selector | What it matches |
|---|---|---|
| Tag | p |
All paragraph elements |
| Class | .notice |
Elements whose class list includes notice |
| ID | #main |
The element with ID main |
| Attribute exists | [href] |
Elements with an href attribute |
| Attribute prefix | [href^="https"] |
Elements whose href begins with https |
| Descendant | article a |
Links anywhere inside an article |
| Direct child | ul > li |
List items directly inside a list |
| Position | li:nth-of-type(2) |
The second li among its same-type siblings |
| Alternatives | h1, h2 |
Either heading type |
Combine patterns to narrow a match. For example, article.story h2 looks for an h2 below an article with class story. Use a space for a descendant relationship and > when the relationship must be direct.
Use CSS selectors with Beautiful Soup
Beautiful Soup provides select() for all matching elements and select_one() for the first match. Both are available on a soup object and on individual tag objects; calling one on a tag scopes the search to that tag’s contents. Beautiful Soup delegates selector handling to Soup Sieve, which is installed alongside Beautiful Soup through pip. Its documentation describes CSS selector support as “a convenience for people who already know the CSS selector syntax.”
Install and run a complete example
Install the package in the Python environment where you will run the script:
python -m pip install beautifulsoup4
This example parses an HTML string, selects elements, and reads their text and attributes:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
from bs4 import BeautifulSoup
html = """
<main>
<article class="story">
<h2>A sample story</h2>
<a href="/read">Read more</a>
</article>
<article class="story">
<h2>Another story</h2>
<a href="https://example.com/another">Read more</a>
</article>
</main>
"""
soup = BeautifulSoup(html, "html.parser")
# Return a list of all matching elements.
headings = soup.select("article.story h2")
for heading in headings:
print(heading.get_text(strip=True))
# Return the first matching element, or None if no match exists.
first_link = soup.select_one("article.story a[href]")
if first_link is not None:
print(first_link.get_text(strip=True), first_link["href"])
# A tag can scope a search to one part of the tree.
first_article = soup.select_one("article.story")
if first_article is not None:
print(first_article.select_one("h2").get_text(strip=True))
select() returns a list, including an empty list when there are no matches. select_one() returns a matching tag or None; check for None before reading text or an attribute. To retrieve visible text from a tag, get_text(strip=True) is useful. To retrieve an attribute, use dictionary-style access, such as tag["href"]; first test that the element actually has the attribute if the markup is not guaranteed to include it.
When a selector is a poor fit
CSS selectors are useful for structural matches, but they are not the only search API in Beautiful Soup. If you need text-based filtering, custom conditions, or parent/child navigation, the library’s other search methods or direct tree traversal may be clearer. Pick the simplest method that expresses the condition you actually need.
Use CSS selectors with lxml
lxml provides a CSS-selector interface through lxml.cssselect.CSSSelector. It translates a CSS selector into XPath and evaluates it against an lxml document or element. Install lxml and the independent cssselect package in the same environment:
python -m pip install lxml cssselect
Runnable example:
from lxml.cssselect import CSSSelector
from lxml.html import fromstring
html = "<main><p class='intro'>Hello</p><p>Other text</p></main>"
document = fromstring(html)
selector = CSSSelector("main > p.intro")
matches = selector(document)
for match in matches:
print(match.text_content())
CSSSelector can be called with a document or an element and returns matching nodes. lxml also documents an Element.cssselect() convenience method. If you already work with XPath, CSS-to-XPath translation can fit selectors into an XPath-based workflow; the translated expression still needs an XPath-capable evaluator such as lxml to retrieve nodes.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Translate a selector directly
The separate cssselect project exposes translation without retrieving elements itself. For HTML, use HTMLTranslator; for generic XML, use GenericTranslator. Catch selector errors when the string may come from user input or another tool:
from cssselect import HTMLTranslator, SelectorError
try:
xpath = HTMLTranslator().css_to_xpath("div.content")
print(xpath)
except SelectorError as error:
print(f"Invalid or unsupported selector: {error}")
The translated XPath is an expression, not a list of results. The cssselect documentation distinguishes malformed syntax from selector expressions it does not support. lxml reports support for most Level 3 selectors, while cssselect describes CSS3 selector translation to XPath 1.0; neither statement means that every modern browser selector works in every parser setup.
Another option: selectolax
selectolax is an HTML5 parsing library with a CSS-selector interface. Its project documentation retrieved for this article identifies version 0.4.12, calls the Lexbor backend preferred, and describes the Modest backend as first-generation and deprecated. These version and backend details can change, so check the project’s current installation and API documentation before adopting it. The project describes selectolax as fast; that is the project’s characterization, not an independently measured comparison here.
Choose a parser based on the job
| Your need | Consider | What to know |
|---|---|---|
| A convenient parsing and search API | Beautiful Soup | select() and select_one() use Soup Sieve; the search can be scoped to a tag. |
| XPath integration or compiled selectors | lxml with cssselect | CSS selectors compile to XPath; lxml documents precompilation as a potential speed improvement. |
| An HTML5 parser with CSS selection | selectolax | Its documentation describes this role and currently identifies Lexbor as the preferred backend. |
Beautiful Soup’s documentation recommends lxml when CSS selectors are all you need and describes it as a lot faster. That is the library’s own recommendation, not a universal benchmark. Parsing speed and total runtime depend on the input, selector, workload, and environment. If speed matters, measure your actual task rather than choosing on an unqualified ranking. For repeated lxml queries, its documentation says precompiling a CSSSelector or XPath can provide a substantial speedup; treat that as a documented potential benefit and verify it with your workload.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Why a browser selector may not work in Python
A selector copied from browser developer tools is not guaranteed to work with every Python selector engine. The browser and the parser may support different parts of CSS, and the browser may be inspecting a live DOM that differs from the HTML given to Python. The target might have been inserted by JavaScript, be inside a different document context, or depend on a page state that a static response does not include.
- Check the input first. Print or save the HTML passed to the parser and search it for the target text, class, or ID. If the element is missing, changing the selector cannot make it appear.
- Reduce the pattern. Try a stable class or tag selector such as
.priceorarticle a, then add one condition at a time. - Verify the engine. Consult the chosen package’s supported selector documentation when using newer pseudo-classes or other advanced syntax.
- Prefer stable attributes. Long selectors that depend on generated classes or deeply nested structure can break when a site changes its markup. Use a meaningful class, ID, or attribute when available.
Common problems and fixes
The result is empty
An empty list from select() means no node in the parsed tree matched. Confirm that you parsed the intended response, that the selector uses the right class, ID, and relationship, and that the target is present in that HTML. For a class use .name; for an ID use #name; for an attribute use [name].
select_one() returns None
This is the first-match version of the same problem, not an exception. Guard against a missing match before accessing its text or attributes. If the page can legitimately omit the element, decide whether that case should be skipped, reported, or handled with a default.
The selector works in one library but not another
Selector support is engine-specific. cssselect translates CSS3 and raises an expression error for unsupported selector expressions; lxml documents support for most Level 3 selectors; Beautiful Soup relies on Soup Sieve. Check the relevant engine’s supported syntax and replace unsupported features with a simpler selector or a different query method.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
The target appears in the browser but not in the parsed HTML
Inspect the actual markup passed to Python. A browser may show content added after the initial response by client-side JavaScript; parsing the initial HTML alone does not establish that such content is present. You need an input source that contains the element before selecting it. Keep the distinction clear: selector libraries search their parsed tree, while obtaining or rendering page content is a separate part of the workflow.
The scraper breaks after a site update
Compare the current HTML with the structure your selector assumes. Narrow selectors can depend on incidental nesting or generated class names. Replace brittle pieces with the most stable attributes available, and add a check for a missing match so a markup change produces a useful error rather than a later failure on attribute access.
Or skip the browser setup
If your goal is to inspect a rendered page visually rather than extract elements from a Python-parsed tree, ScreenshotNeo is a screenshot API and MCP server for developers. One request returns a screenshot or PDF; its CSS-selector capture option can target an element in a screenshot workflow. A screenshot is not a replacement for Beautiful Soup or XPath when you need structured text and attributes.
For example, this Python request saves a WebP screenshot of a URL:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
See the ScreenshotNeo API documentation for request options and response details. Before capture it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots. Learn more at ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.
Frequently Asked Questions
Do I need a browser installed to use Beautiful Soup selectors?
No. Beautiful Soup’s selector methods search the tree created from the markup you pass to it; the browser is not part of that selector call.
Can Python CSS selectors return an element’s text and links?
Yes. After selecting a tag, read its text with the library’s text method and retrieve attributes such as href from the tag.
Is a CSS selector the same thing as XPath?
No. They are different query syntaxes. lxml’s CSSSelector translates CSS into XPath internally, while Beautiful Soup exposes CSS selectors through Soup Sieve.
Recommended Free Tools
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

