☰ See All Chapters |
Relative XPath in Selenium
XPath is the xml path of an element in the html tree along with certain conditions and attributes forming an expression. XPath is one of the locator in selenium using which we identify objects or elements when we are unable to locate the elements by using ID, class, name and tag name. If elements are not static in page and dynamically changing then XPath locator is the useful locator.
In Absolute XPath, we write the path of the element right from the root node and hence, the expression for absolute XPath is lengthy. In order to reduce the length of the expression, we go for Relative XPath. In Relative XPath, we use double forward slash ( // ), which represents any descendant.
Considering the below sample html code, below are the different relative XPath examples
<html> </head> <body> <table align="center" width=90% cellspacing="2" cellpadding="2"> <tr> <td><a href="#">A</a></td> <td><a href="#">B</a></td> </tr> <tr> <td><a href="#">C</a></td> <td><a href="#">D</a></td> </tr> </table> </body> </html> |
Relative XPath expressions | Matching Element |
//tr[1]//td[1] | A |
//tr[1]//td[2] | B |
//tr[2]//td[1] | C |
//tr[2]//td[2] | D |
//tr[1]//td | AB |
//tr[2]//td | CD |
//td[1] | AC |
//td[2] | BD |
//tr[1]//td[1] | //tr[2]//td[2] | AD |
//tr[1]//td[2] | //tr[2]//td[1] | BC |
//tr[1]//td | //tr[2]//td[1] | ABC |
//tr[1]//td | //tr[2]//td[2] | ABD |
//tr[1]//td | //tr[2]//td | ABCD |
Using Google Chrome browser to find the relative XPath
Right click web element and select Inspect Element. It will launch a window containing source code of the page and in the code the html tag which is rendering the selected element will be highlighted. Now Right click on that code> Select Copy > Select Copy XPath
What is the difference between ‘/’ and ‘//’ ?
“/” refers to the immediate child element in the html tree. “//” refers to any element in the html tree. It also represent any descendant.
Derive an XPath which matches all the links (a tags) present on a web page?
//a
Derive an XPath which matches the entire image present on a web page?
//img
Derive an XPath which matches all the links (a tags) and images present on a web page?
//a | //img
Derive an XPath which matches all the 2nd links (a tags) present on a web page?
//a[2]
Derive an XPath which matches all the links (a tags) present inside a table present on a web page?
//table//a
What is the difference “//a” and “//table//a “ ?
//a → refers to all the links present on the webpage.
//table//a → refers to all the links present within all the tables present on the webpage.
All Chapters