Skip to main content
BETAUnder active development. Some features may not work as expected.

CSS Selectors for Web Scraping: Complete Guide

beginner

A CSS selector is a pattern used to select and target specific HTML elements on a web page. In web scraping, CSS selectors are the primary way to locate the data you want to extract from a page's HTML structure.

Essential Selectors for Scraping

SelectorWhat it matchesExample
.classElements with a class.product-card
#idElement with an ID#main-content
tagAll elements of a typeh2, a, div
parent childNested elements.card .price
parent > childDirect children onlyul > li
[attr=value]Attribute match[data-id="123"]
:nth-child(n)Nth elementtr:nth-child(2)

Using CSS Selectors in Python

python
# BeautifulSoup
soup.select(".product-card .price")       # all matching
soup.select_one("h1.title")               # first match

# Playwright page.query_selector_all(".product-card") # all matching page.query_selector("h1.title") # first match

# Scrapy response.css(".product-card .price::text").getall() response.css("h1.title::text").get()

Tips for Finding Good Selectors

  1. 1.Use your browser's DevTools: Right-click an element, click "Inspect", then right-click the element in the Elements panel and copy the selector
  2. 2.Prefer class names over position: .price is more stable than div:nth-child(3) > span
  3. 3.Use data attributes: [data-product-id] is often more reliable than class names
  4. 4.Test in the console: Use document.querySelectorAll(".your-selector") in the browser console to verify

Common Scraping Patterns

  • Extract text: .select_one(".price").text
  • Extract link: .select_one("a").get("href")
  • Extract image: .select_one("img").get("src")
  • Extract all items in a list: .select("ul.results > li")

Learn CSS Selector hands-on

This glossary entry covers the basics. The Master Web Scraping course teaches you to use css selector in real projects across 16 in-depth chapters.

Get Instant Access — $19

$ need_help?

We're here for you