CSS Selectors VS XPath

Class

XPath

//*[@class='a1']

CSS Selector

.a1

Id

XPath

//*[@id='some_id']

CSS Selector

#some_id

Element (Tag)

XPath

//div

CSS Selector

div

Attribute

XPath

//*[@some_attribute='some_value']

CSS Selector

[some_attribute='some_value']

Relation Between Elements

 

div, p

Selects all <div> elements and all <p> elements

Relation Between Elements

 

div p

Selects all <p> elements inside <div> elements (all children and grandchildren)
 

Relation Between Elements

 

div > p

Selects all <p> elements where the parent is a <div> element (direct children only)
 

Relation Between Elements

 

div + p

Selects all <p> elements that are placed immediately after <div> elements
 

Contains

 

[some_attribute*='some_value']

Example

a[href*="w3schools"]

Selects every <a> element whose href attribute value contains the substring

Examples

XPath

//*[@class='a1'][@href='/ru/electronics/']

CSS Selector

.a1[href='/ru/electronics/']

Examples

XPath

//*[@class='page_header_head']/h1

CSS Selector

.page_header_head > h1

or more flexible

.page_header_head h1

Examples

XPath

//tr[contains(@id,'tr_') and not(contains(@id,'tr_bnr'))]

CSS Selector

[id*='tr_']:not([id*='tr_bnr'])

Examples

XPath

//img[@id='logo'][@class='page_header_logo']

CSS Selector

img#logo.page_header_logo

Drawback

CSS Selector does not contain text() function as in XPath

CSS Selectors VS XPath

By Ilja Pavlovs

CSS Selectors VS XPath

  • 599