Selenium Locators Tutorial: Learn How to Identify Web Elements Using XPath in Selenium with Examples
In the previous tutorial, we introduced you to another automation testing tool named Firebug. We also created our automation script manually using Firebug and its capabilities. We also learned to affix the desired modifications to our script.
Moving ahead, in this tutorial, we will have a look at the various locators in Selenium and their accessibility techniques to build test scripts. This tutorial comprises a detailed introduction to various types of locators.
This is our 5th tutorial in the Selenium Tutorial series.
Table of Contents:
Understanding Selenium Locators
What is a Locator
The locator can be termed as an address that identifies a web element uniquely within the webpage. Locators are the HTML properties of a web element that tell Selenium about the web element it needs to act on.
There is a diverse range of web elements. The most common among them are:
- Text box
- Button
- Drop Down
- Hyperlink
- Check Box
- Radio Button
Types of Locators
Identifying these elements has always been a very tricky subject and thus it requires an accurate and effective approach. We can assert that the more effective the locator, the more stable will be the automation script. Essentially, every Selenium command requires locators to find the web elements. Thus, to identify these web elements accurately and precisely, we have different locators.
Now let’s understand further by exercising each of them independently.
Before we start with the locators, let me take a moment to introduce the application under test. We would use “https://accounts.google.com/” to locate different web elements using different locator types.
Using ID as a Locator
The best and the most popular method to identify web elements is to use ID. The ID of each element is alleged to be unique.
In this sample, we would access the “Email” text box present in the login form at gmail.com.
Finding an ID of a web element using Firebug
Step #1: Launch the web browser (Firefox) and navigate to “https://accounts.google.com/”.
Step #2: Open Firebug (either by pressing F12 or via tools).
Step #3: Click on the inspect icon to identify the web element.
Step #4: Hover on the web element (Email textbox in our case) on which we desire to perform some action. In the Firebug section, one can see the corresponding HTML tags being highlighted.
Step #5: Be cognizant of the ID attribute and note it. Now we need to verify if the ID identified can find the element uniquely and flawlessly.
Syntax: id = id of the element
In our case, the id is “Email”.
Alternative approach:
Instead of following steps 2 to 4, we can directly locate/inspect the web element by right-clicking on the web element (Email Textbox) whose locator value we need to inspect and clicking on the option “Inspect Element with Firebug”. Thus, this click event triggers the expansion of the firebug section and the corresponding HTML tag would be highlighted.
Verify the locator value
Assuming that the browser is open and is re-directed to “https://accounts.google.com/”.
Step #1: Launch Selenium IDE.
Step #2: Click on the first row in the editor section.
Step #3: Type “id=Email” i.e. the locator value in the target box.
Step #4: Click on the Find Button. If the provided locator value is legitimate then the Email textbox will be highlighted with a yellow color with a fluorescent green border around the field. If the locator value provided is incorrect, an error message will be printed in the log pane at the bottom of Selenium IDE.
Case #1 – Locator Value = Correct
Case #2 – Locator Value = Incorrect
Step #5: To verify further, a user can also execute the “type” command against the target by providing some value in the “Value” field. If the execution of the command enters the specified value in the Email text box that means the identified locator type is correct and accessible.
Using ClassName as a Locator
There is only a subtle difference between using ID as a locator and using the class name as a locator.
In this sample, we would access the “Need Help?” hyperlink present at the bottom of the login form at gmail.com.
Finding a classname of a web element using Firebug
Step #1: Locate/inspect the web element (“Need help?” link in our case) by right-clicking on the web element whose locator value we need to inspect and clicking on the option “Inspect Element with Firebug”.
Step #2: Be cognizant of the class name attribute and take note of it. Now we need to verify if the class name identified can find the element uniquely and accurately.
Syntax: class = class name of the element
In our case, the class name is “need-help-reverse”
Verify the locator value
Step #1: Type “class= need-help-reverse” in the target box in the Selenium IDE.
Step #2: Click on the Find Button. Notice that the hyperlink will be highlighted with a yellow color with a fluorescent green border around the field.
(Click to view enlarged image)
Using name as a Locator
Locating a web element using the name is very much analogous to the previous two locator types. The only difference lies in the syntax.
In this sample, we would access the “Password” text box present in the login form at gmail.com.
Syntax: name = name of the element
In our case, the name is “Passwd”.
Verify the locator value
Type “name= Passwd” in the target box and click on the Find Button. Notice that the “Password” textbox will be highlighted.
Using Link Text as a Locator
All the hyperlinks on a web page can be identified using Link Text. The links on a web page can be determined with the help of an anchor tag (<a>). The anchor tag is used to create the hyperlinks on a web page and the text between the opening and closing of anchor tags constitutes the link text (<a>Some Text</a>).
In this sample, we would access the “Create an account” link present at the bottom of the login form at gmail.com.
Finding a link text of a web element using Firebug
Step #1: Locate/inspect the web element (“Create an account” link in our case) by right-clicking on the web element whose locator value we need to inspect and clicking on the option “Inspect Element with Firebug”.
Step #2: Be cognizant of the text present within the <a> </a> tags and take note of it. Hence this text will be used to identify the link on a web page uniquely.
(Click to view enlarged image)
Syntax: link = link text of the element
In our case, the link text is “Create an account”.
Verify the locator value
Step #1: Type “link=Create an account” i.e. the locator value in the target box in Selenium IDE.
Step #2: Click on the Find Button. Notice that the link would be highlighted with yellow color with a fluorescent green border around the field.
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 similar to HTML tags. Both the markup languages and since they fall under the same umbrella, XPath can 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 on a web page. Thus, Xpaths can 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 Xpaths but most of the time, the generated Xpaths cannot identify the web element correctly.
- While creating xpath, the user should know 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 the 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 reiterating 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 predefined rules and protocols.
In this sample, we would access the “Google” image present at the top of the login form at gmail.com.
Creating an 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 fluorescent green border around the field.
Conclusion
Here are the cruxes of this article.
- Locators are the HTML properties of a web element that tell Selenium about the web element on which it needs to perform actions.
- There is a wide range of web elements that a user may have to interact with regularly. Some of them are Textbox, Button, Drop Down, Hyperlink, CheckBox, and Radio Button.
- With the varied range of web elements comes a vast province of strategies/approaches to locate these web elements.
- Some of the extensively used locator types are ID, ClassName, Link Text, XPath, CSS Selectors, and Name.
Note: Owing to the fact that creating CSS Selector and XPath requires a lot of effort and practice, thus more sophisticated and trained users only exercised the process.
In this tutorial, we learned different types of locators including Selenium Xpath.
Next Tutorial #6: In continuation with this Selenium Locator types tutorial, we will learn how to use CSS Selector as a Locator.
Do you have questions? Let us know in the comments. We will try to resolve all.
Hi,
Can you please provide an example of how to correct an error in Selenium IDE by using firepath and firebug? Example provide “command”, “target”, and “value” by showing in video how one can find element and make the automation testing work?
I am loving this tutorial series. I just tried the xPath option using selenium IDE by writing Target=//img[@class=’logo’] for base url https://accounts.google.com/, but no success, Can you please let me know what I did wrong here?
Rest everything is fine, please share some assignments at the end of each tutorial which will help in further learning
ya its very nice,but can y tell me how to use xpath,
Great tutorial guys. You explained everything well. I do wish you guys talked about x path some more. It’s a tough technique and should be covered in more detail.
//a[contains(text(),’new booking’)]
i have created the above dynamic xpath so do we have a strong way to handle the situation when the element name changes from “a” to some other element name for example class or span.
//class[contains(text(),’new booking’)]
Hi,
Facing issue as I am trying to record a login and logout functionality for an application.
While recording selenium as identified element as link=logout but when I am trying to playback the script it is not identifying the link LOGOUT and execution stops with [error] Element link=LOGOUT not found
when I am trying with button find it is still identifying
an element as link=LOGOUT.
Can you please suggest what could be the problem?
Thanks
Hi, very nice explanation of xpath. However, I am interested to know how do we write xpath manually without using selenium IDE? Can you explain the google example with firepath and manually? Please give some examples with screen shots and explain. I love this site. Great start of all the articles, very nice examples with screen shots which makes it very easy to comprehend. Thank you!
sir,
I want to help
how to inspect the element angular based application with the help of selenium with python .
Thank you very much for the tutotials. When we are supposed to use Xpath instead of other locators ? is there any special scenarios/cases ?
Thank you for sharing the tutorial. it is very good.
Thanks Shruti,
tried with //img[@class=’logo’] and it works perfectly fine.
ok good…
I need to find an object in a report that has no inspect option.
Half of the links suggested in tutorial are outdated. plz update ur page first.
nd plz reply to thee comment sectio
@Anjali
Thank you for the kind words.
Hi, i am the new learner of selenium automation.i have two search buttons with same features in two panel of the same page.And want to hit the second search button.Can some one help me how to locate using xpath.Below is the code for that
Even i tried with below xpath checker but no result
WebElement search = driver.findElement(By.xpath(“//id(‘table4’)/tbody/tr[7]/td/input[2]”));
what is the replacement for firebug and firepath for finding elements ?
You can try down with relative xpath because it is more accurate as compared to absolute one and also a good practice to use it inside your code.
Selenium does not provide facility to use data-test-id, which is unique id provided by Pega. This is the biggest limitation with Selenium for Pega application.
If Selenium can find a way to use data-test-id then it would be very much helpful to automate Pega applications.
Very nice.It is very useful to study about the selenium automation.
@Manoranjan Sahoo
Hi,
You can try this:
1. Right click on the button and select “Inspect Element with Firebug” option. This will highlight the HTML code for your button in the Firebug.
2. Now right click on the HTML code and select “Copy XPath” option.
3. Now in Selenium IDE type “Click” in command field and paste the XPath copied in previous step prefixing it with “/” in the Target field, so the XPath in the Target field would be prefixed with “//”
4. Click on “Find” button, this will highlight the second button.
4. And execute this test script.
It should work. Let me know if it works for your scenario.
How to identify web elements in Internet Explorer?
Hi, can u plzz tel me how to write xpath for dynamic web elements.. ??
Hi
while choosing name as locator for the textbox password
I have given name=passwd in the target box and clicked on find , but error is thrown saying locator not found name=passwd . Please let me know why this error is occcured and the steps to prevent it
Regards,
Padmasree GL.
Hi Shruti,
When I check the Xpath of Google logo i can see xpath as “id(‘hplogo’)”. Also if I enter the xpath “//img[@class=’logo’]” and try to find then I get log as [error] locator not found: //img[@class=’logo’]. Can you please help me with this.
how to identify the object for this…Current
I used yahoo for trial test. i created a script with valid user id & Password. First time it works fine. When i ran next time scrpt is NOT identify the user name and password and gave the error . what should be the issue ?
The Google sign in GUI has changed since video. today is 7/30/15 and although I have installed the Xpath add-on in Firefox, Selenium is not finding the target element. For an id of the “Next” button, XPath returns “id(‘Next’). When I paste that into the Target textbox in Selenium IDE and click “Find” the following error is logged: [error] locator not found: id(‘next’). I could change the target to read id=Next, but that isn’t XPath, that is using the id to find the element. Please let me know how to find the XPath using this tool. The XPath displays the element in the lower Results pane, but if I paste that path into Selenium, I keep getting errors. Thanks.
Great tutorials for beginners with step by step teaching. The selenium documentation and online guides I’ve been finding are poorly written and assumes the person using selenium is an advanced programmer.
Nice.Much descriptive 🙂
Hi,
I have pop windows if a select file ‘save’ with name and description to fill , and another pop up window if I select ‘Save As’. The both pop up have same ok button. The ‘ OK’ button has same id and same xpath. and it is not able to click. Pls send the answer if you possible.
I’ve also found that my “Google” logo xpath is slightly different due to an update on my browser.
now it’s “//div[@class=’logo logo-w’]”
I’ve also discovered on my end that in most cases you can use “*” in place of “div”
e.g. “//*[@class=’logo logo-w’]”
🙂
Hello,
I have some question selenium can locator script or tag in header of page?
Example:
@QTP Tutorial
Thank you for the appreciation and suggestion.
We would surely check if we could include more details on Xpaths.
Hi, I am trying to locate an element on area/map tag. The element is never clicked. I tried using chrome/firefox both and different locator techniques like CSS, xpath etc. Below is the code, when identified using firebug. Please provide your inputs.
//(HTML code of the element)
One page have 10 url’s(hyperlinks)
without locator value how test the url’s?
In web page some web elements are there all the web element are in the same class name so i have to click on 7 web element how i should do that ?
how identify locator for dropdownlist in manual scripting
Can you please cover Cocedeption with WebDriver
I’m trying to write absolute Xpath. Once I click on evaluate, getting an error saying that ‘No matching nodes’. Can anyone please explain how to write absolute xpath.
Is there a way to use XPATH to get ID of a webelement using %, something like SQL Query “Select * from tab where name like ‘TABLE_NAME%_01%’;”
I tried something like this: //*[contains(@id,’oj-select-choice-searchField_ojcomposite%_1′)] but doesn’t work for me to identify object on page.
My issue is that the ID for button changes plus, the next button with same name also has index, something like below:
id=”ojChoiceId_searchField_ojcomposite15_0_selected”
id=”ojChoiceId_searchField_ojcomposite15_1_selected”
id=”ojChoiceId_searchField_ojcomposite15_2_selected”
How do you get the proper XPATH for this scenario?
Thanks
–Ike
Hi Shruti,
I find these tutorials easy to understand and awesome!
Keep up the great work!
Thanks for using images too.
I’m having an issue:
– I use //img[@class=’logo’]
and I get back
[error] locator not found: //img[@class=’logo’]
– I also tried //image[@class=’logo’]
and I get back
[error] locator not found: //image[@class=’logo’]
Any suggestions? Thanks in advance :))
Nice Blog. It’s very informative for new tester.
hi, i am trying to locator the element, but id of it always change after reload page, how i can do with it?
Require: i use Selenium IDE and i need get element in Projects
Problem: ID of div ( <div id="dgrid_2-row-0.7051704519707559") always change after reload page
Projects
Manage projects for the website
to find xpath for a specific element we can use firepath which is an extension to firebug….These are the extensions in firefox
How do we find Xpath in Chrome, can you please help on this with an example.
Thank you very much for the tutorials. We would like to see more on XPATH to locate siblings and parents(Moving Xpaths). Eagerly waiting for complete Webdriver tutorials. Again thanks for the effort 🙂
Hello,
This was very well explained as I have already directly started to learn Selenium WebDriver and used different locators for different elements. But, I did not had a clear idea when to use what locators and also the differences.
Regards,
Chirag
good tutorial
It will be beneficial to me if you write the programs as well
I recently read that Firebug was being deprecated. Is there a replacement you could recommend?
@ssut
please try with [@id=’Email’]
How to identify radio buttons using selenium IDE when name is common
The Target field is inaccessible in Selenium IDE. What do I do to make it active?
Hi,
How to select the date using date picker in Selenium.
I could able to select the current date by clicking on the button “Today” in the calendar.
To select past or future dates, it is a problem.
as it is not recognizing the drop-downs for years or months in the calendar.
Please suggest.
@Hitesh
Thank you for the appreciation.
Try //img[@class=’logo’] instead of //image[@class=’logo’]
Please let me know if it doesn’t work even now.
How can I differentiate between 5 webelement having same xpath, id , name everything. ?
I am able to find the web element in firefinder by writng xpath but when i try to execute the script i am getting NoSuchElementFound Exception.I tried with writng xpath in different ways..plz anyone help me its urgent..Thank you
I had given the xpath but still i am facing the “element not visible” error.Please give me the solution for this kind of issue.
Hi Shruti,
Wonderful article and very well explanation, but at last i tried step1 and step2 for xpath and observed that i am getting following error:
“[error] locator not found: //image[@class=’logo’]”
I am not sure why it is coming, could you explain this xpath locator in detail?
Thanks in advance.
i have problem in using id as locator.
when i write “id=Email” in type field..it is correct.but still its give an error.locator not found
Hi Shruthi,
The tutorial is really very helpful for the beginners. I am in Tutorial 5 now and when i am trying to use //img[@class=’logo’] in Selenium IDE and click on Find, its unable to locate. I am getting “locator not found” error. Can you please guide?
Thanks & Regards,
Monika
Hi, If the web page is developed by .net which not supported by selenium then how you can automate that web page or web elements? please tell as it is asked in interview
This is really very useful. Thank you so much guys. Really appreciated 🙂
Heard about Xpath Checker first time. Tahnks for letting us know. I think this add on is available for all firefox versions even latest one.
I recently start working with selenium and didn’t have a clue, I have to thank you because of this tutorial I know now selenium tools and made my work easier.
Good work and please continue sharing your knowledge with us
Nice artical.
Thanks.