How to Identify Web Elements Using Selenium Xpath and Other Locators – Selenium Tutorial #5

In the previous tutorial, we introduced you with another automation testing tool named as Firebug. We also created our own automation script manually using Firebug and its capabilities. We also learned to affix desired modifications into our script.

Moving ahead, in this tutorial we would have a look at the various types of locators in Selenium and their accessibility technique to build test scripts. Thus this tutorial is comprised of the detailed introduction to various types of locators.

This is our 5th tutorial in Selenium Tutorial series.

What is Locator?

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 which tells the Selenium about the web element it need to perform action on.

Using Selenium Xpath and Other Locators

There is a diverse range of web elements. The most common amongst 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. Thereby, we can assert that more effective the locator, 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 types of locators.

Types of Locators in Selenium 1

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 be using “https://accounts.google.com/” for locating different types of web elements using different locator types.

Using ID as a Locator

The best and the most popular method to identify web element is to use ID. The ID of an each element is alleged to be unique.

Types of Locators in Selenium 2

In this sample, we would access “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.

Selenium Locators 1

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.

Selenium Locators 2

Step 5: Be cognizant about the ID attribute and take a note of it. Now we need to verify if the ID indentified is able to find the element uniquely and flawlessly.

Syntax: id = id of the element

In our case, the id is “Email”.

Alternative approach:

Instead of following step 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 firebug section and the corresponding html tag would be highlighted.

Selenium Locators 3

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 yellow color with a florescent green border around the field. If the locator value provided is incorrect, an error message would be printed in the log pane at the bottom of Selenium IDE.

Case 1 – Locator Value = Correct

Selenium Locators 4

Case 2 – Locator Value = Incorrect

Selenium Locators 5

Step 5: In order to verify further, user can also execute “type” command against the given 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 classname as a locator.

In this sample, we would access “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 about the classname attribute and take a note of it. Now we need to verify if the classname indentified is able to find the element uniquely and accurately.

Selenium Locators 6

Syntax: class = classname of the element

------------

In our case, the classname 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 yellow color with a florescent green border around the field.

(Click to view enlarged image)

Selenium Locators 7

Using name as a Locator

Locating a web element using name is very much analogous to previous two locator types. The only difference lies in the syntax.

In this sample, we would access “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

Step 1: Type “name= Passwd” in the target box and click on the Find Button. Notice that the “Password” textbox would be highlighted.

Using Link Text as a Locator

All the hyperlinks on a web page can be indentified using Link Text. The links on a web page can be determined with the help of anchor tag (<a>). The anchor tag is used to create the hyperlinks on a web page and the text between opening and closing of anchor tags constitutes the link text (<a>Some Text</a>).

In this sample, we would access “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 about the text present within the <a> </a> tags and take a note of it. Hence this text will be used to identify the link on a web page uniquely.

(Click to view enlarged image)

Selenium Locators 8

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 florescent green border around the field.

Selenium Locators 9

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.

Selenium Locators 10

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.

Selenium Locators 11

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.

Selenium Locators 12

Conclusion

Here are the cruxes of this article.

  • Locators are the HTML properties of a web element which tells the 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 on a regular basis. Some of them are: Text box, Button, Drop Down, Hyperlink, Check Box, 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 efforts and practice, thus the process is only exercised by more sophisticated and trained users.

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.

Any queries? Let us know in comments. We will try to resolve all.

Recommended reading

50 comments ↓

#1 Anjali Mone

Thank you for sharing the tutorial. it is very good.

#2 QTP Tutorial

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.

#3 Shruti Shrivastava

@Anjali

Thank you for the kind words.

#4 Shruti Shrivastava

@QTP Tutorial

Thank you for the appreciation and suggestion.
We would surely check if we could include more details on Xpaths.

#5 hitesh

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.

#6 Shruti Shrivastava

@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.

#7 Gopi

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 :)

#8 hitesh

Thanks Shruti,
tried with //img[@class=’logo’] and it works perfectly fine.

#9 Papak

Thank you very much for the tutotials. When we are supposed to use Xpath instead of other locators ? is there any special scenarios/cases ?

#10 altaf

How to identify web elements in Internet Explorer?

#11 S Balu

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 ?

#12 Nikhil

How can I differentiate between 5 webelement having same xpath, id , name everything. ?

#13 Tanushri

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.

#14 kalpana

How to identify radio buttons using selenium IDE when name is common

#15 annt

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

#16 Arveti

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

#17 Manoranjan Sahoo

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]”));

#18 vaishnavi

@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.

#19 Kapil

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

#20 Ravi

to find xpath for a specific element we can use firepath which is an extension to firebug….These are the extensions in firefox

#21 Manikandan

Hi, can u plzz tel me how to write xpath for dynamic web elements.. ??

#22 Tom

The Target field is inaccessible in Selenium IDE. What do I do to make it active?

#23 Prathibha

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.

#24 ssut

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

#25 writer

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.

#26 Monika

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

#27 Yogesh Aggarwal

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?

#28 Gaurav Khurana

Rest everything is fine, please share some assignments at the end of each tutorial which will help in further learning

#29 Ssingh

@ssut
please try with [@id=’Email’]

#30 Ci weltz

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

#31 Punnawat

Hello,

I have some question selenium can locator script or tag in header of page?

Example:

#32 Andy Sworn

Nice Blog. It’s very informative for new tester.

#33 T.Santhi

Very nice.It is very useful to study about the selenium automation.

#34 Anu

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.

#35 AVINASH

ya its very nice,but can y tell me how to use xpath,

#36 Mukta

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!

#37 SS

Can you please cover Cocedeption with WebDriver

#38 Paul

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 :))

#39 Paul Laguna

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’]”

:)

#40 Dilshad

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?

#41 Amitesh

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.

#42 Rob

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.

#43 Chirag

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

#44 nithin

how identify locator for dropdownlist in manual scripting

#45 mohan

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

#46 padmasree

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.

#47 Shobha

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)

#48 Haresh

This is really very useful. Thank you so much guys. Really appreciated :)

#49 Vasan

How do we find Xpath in Chrome, can you please help on this with an example.

#50 IKE

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

Leave a Comment