We always have concerns about writing Dynamic Xpath. So, I've listed below some ways to write xpath with example. If you face any problem, Contact Us:
1) Based on location
2) Using Single Attributes
3) Using Multiple Attributes
4) Using functions
All examples are based on following HTML Code:
input class="search-field" name="s" placeholder="Search …" title="Search for:" type="search" value=""
1- Based on location
1.1) / (Single Back Slash) - directly after the parent node
Ex-1 : /html/body/div[1]/div[2]/div[2]/div/div/div/div/form/div[1]/div[1]/div[1]/div/div/input
1.2) // (Double Back Slash) - Search in a whole page (DOM) for the preceding string
Ex-1 : //form/div[1]/div[1]/div[1]/div/div/input
2- Using Single Attributes
Syntax:
//tagname[@attributename='value']
Ex1- //input[@type='search']
Ex2- //input[@class='search-field']
Ex3- //input[@name='s']
Ex4- //*[@value='']
3- Using Multiple Attributes
Syntax://tagname[@attributename1='value1' and @attributename2='value2]
Ex 1- //*[@type='search' and @class='search-field']
Ex 2- //*[@value='' and @class='search-field']
4- Using functions
4.1) Using contains() function : Sometimes an element gets identified by a value that could be surrounded by other text, then Contains function can be used:Syntax-
//tagname[contains(@node,'text-here')]
Ex 1- //*[contains(@class,'search-field')]
4.2) Using last() function : Selects the last element out of all input element present
Ex 1- //input[last()]
4.3) Using position() function : Selects the element out of all input element present depending on the positions provided
Ex 1- //input[position()<3 font="">3>
4.4) Using starts-with function : Selects the element out of all input element present depending on the node starting with the specified text:
You can download a whole list of XPath, CSS, DOM identification table as PDF from here