XPath. Tips and tricks

About XPath

XPath is a way to locate elements on a web page – like CSS selectors, but more suitable in some cases. I use it selectors for web page scraping and testing.

Useful XPath selectors

Here is the list of XPath selector examples very useful for me:

Take last child
book/author[last()]
Search element by ID
[@id="availabilityTable"]
Search elements by class name
[@class="ADTprice"]

e.g.

//*[@id="availabilityTable"]/span[@class="ADTprice"]

Note! If target element has many classes, then you should use more complex syntax

//*div[contains(concat(" ",normalize-space(@class)," ")," popIndexValidation ")]/a
Search by name attribute
input[@name="prices"]
Find elements, which have attribute
//*[@foo]
Logic AND in criteria
//input[@name='Sport' and ./author/text()='James Small']
Logic OR in criteria
//input[@type="input" or @type="email" or @type="password"]
Logic NOT in criteria
//a[not(contains(@id, 'xx'))]
Find descendant element with class
//*[@id="HEADING_GROUP"]/descendant::b[@class="rank"]
Find neighbor
<span>
</span>
<a>
   1
</a>

This selector

span/following-sibling::a

Will return <a> tag closes with <span> tag

Get element text except descendant’s text
<p>
   123
   <span>
      456
   </span>
</p>

This selector

p/text()[1]

Will return 123

Find element by inner text
span[contains(text(),"Breakfast Included")]
How to get the XPath selector?

Open target web page in Google Chrome browser and press F12 button, you will see Developer Tools Panel

google chrome developers panel
Google chrome developers panel

Press “Select element” button

Select element button
Select element button

Move your mouse pointer to the target web page element (it will be highlighted by blue color) and click on it. The element markup will be highlighted in the developer tools panel

Target element is highlighted
Target element is highlighted

Right click on the target element’s markup, and in the menu, select Copy -> Copy XPath

Copy XPath
Copy selector

That is it!