Mastering element locating techniques and relative Xpath writing skill
A complete practical guide for writing correct Xpath in any situation
In this practical guide we will not go thru the very beginning or explaining what is Xpath. This is fully practical tutorial to increase your effectiveness and speed in writing Xpath in difficult cases and for dynamically generated locators on your page.
Disassembling the element
Just picking some subject element to have a closer look at the parts it's built from.
Tag name (the very first text value in our element is a tag name - here it's a)
Attribute name (name of the attribute is some text value, it might be separate or in format attribute="some value". For example in this element href)
Attribute value (the value of attribute,in Chrome dev tools comes orange colored, comes after = sign, in "" marks. Here attribute href has the value "/guides")
Attributes might come without values (like _ngcontent in this example)
<text ... - Tag Name
NAME = "VALUE" or NAME - attributes
Just remember simple rule - always start from //
Next after // we need to tell what kind of element to search by writing a Tag Name of element, like that //a or we can set to search all element with //*
Our element is a , so first part of our Xpath is //a
After //a we can make search more accurate, by telling which attributes should our element contain with opening [ ] .
Remember the href attribute? Attribute in xpath should start with @
But we can make it even more accurate, providing a value of attribute
By the way it is almost the same as //*[@href='/guides']
After one element we can look into child element from this one.. or parent
Just remember the syntax :
Parent element of selected element
//a[@href='/guides']//parent::and here everything repeats from beginning - tag name, attribute..