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
Search element by ID
Search elements by class name



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
Find elements, which have attribute
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
Find neighbor

This selector


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

Get element text except descendant’s text

This selector


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!