Using Xpath as a Locator
Xpath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being mark up languages and since they fall under the same umbrella, xpath can be used to locate HTML elements.
The fundamental behind locating elements using Xpath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.
Xpath can be created in two ways:
Relative Xpath
Relative Xpath begins from the current location and is prefixed with a “//”.
For example: //span[@class=’Email’]
Absolute Xpath
Absolute Xpath begins with a root path and is prefixed with a “/”.
For example: /html/body/div/div[@id=’Email’]
Key Points:
- The success rate of finding an element using Xpath is too high. Along with the previous statement, Xpath can find relatively all the elements within a web page. Thus, Xpaths can be used to locate elements having no id, class or name.
- Creating a valid Xpath is a tricky and complex process. There are plug-ins available to generate Xpath but most of the times, the generated Xpaths fails to identify the web element correctly.
- While creating xpath, user should be aware of the various nomenclatures and protocols.
Selenium Xpath Examples
Xpath Checker
Creating Xpath becomes a little simpler by using Xpath Checker. Xpath Checker is a firefox add-on to automatically generate Xpath for a web element. The add-on can be downloaded and installed like any other plug-in. The plug-in can be downloaded from “https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/”.
As soon as the plug-in is installed, it can be seen in the context menu by right clicking any element whose xpath we want to generate.
Click on the “View Xpath” to see the Xpath expression of the element. An editor window would appear with the generated Xpath expression. Now user has the liberty to edit and modify the generated Xpath expression. The corresponding results would be updated cumulatively.
Note that the Xpath Checker is available for other browsers as well.
But re-iterating the fact, that most of the times, the generated Xpaths fails to identify the web element rightly. Thus, it is recommended to create our own Xpath following the pre defined rules and protocols.
In this sample, we would access “Google” image present at the top of the login form at gmail.com.
Creating a Xpath of a web element
Step 1: Type “//img[@class=’logo’]” i.e. the locator value in the target box within the Selenium IDE.
Syntax: Xpath of the element
Step 2: Click on the Find Button. Notice that the image would be highlighted with yellow color with a florescent green border around the field.