☰ See All Chapters |
Relative xpath in Puppeteer
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 puppeteer using which we identify objects or elements when we are unable to locate the elements by using ID, class, name and tagname. If elements are not static in page and dynamically changing then xpath locator is the useful locator.
xpath are of 2 types:
Relative xpath
Absolute xpath
Relative xpath
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
Difference between “//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