How do CSS selector combinators work?

CSS selector combinators define relationships between elements, enabling precise targeting in web scraping.

Descendant combinator (space):

Selects all matching descendants at any nesting level:

  • div.product a finds all links inside product divs, regardless of depth

Child combinator (>):

Selects only direct children:

  • ul > li matches list items that are immediate children of a ul, skipping nested lists

Adjacent sibling combinator (+):

Selects the element immediately following another:

  • h2 + p targets the first paragraph after each h2

General sibling combinator (~):

Selects all siblings after an element:

  • h2 ~ p finds all paragraphs following an h2 within the same parent

Combining combinators:

These combinators are powerful when combined:

  • .listing > div.item:first-child > h3.title precisely targets the title of the first item in each listing

Writing resilient selectors:

Understanding combinators helps you write selectors that are resilient to HTML changes:

  • article p is more flexible than div > div > article > div > p
  • The first works regardless of intermediate wrapper divs
  • The second breaks if the DOM structure changes even slightly

Scoping selections:

When scraping structured content like product listings or data tables, combinators let you scope your selections to specific containers, preventing accidental matches from headers, footers, or sidebars.

Related Questions