Locating elements is indeed a nightmare because of the complexity of finding the web elements in the webpage and automating them. To simplify this task, we use something known as locators in Selenium. In this article, I will give you a brief insight into the different types of locators, along with relevant examples. If you wish to learn the easiest way to locate elements on a webpage, you can check out the Selenium Training.
If you want to master the concepts of Selenium from a Certified Selenium Expert, you can check out the video below, where these topics are covered on a broader gauge.
Locators In Selenium Webdriver | Selenium Training | Edureka
What are Locators in Selenium?
Locators are defined as an address that identifies a web element uniquely within the webpage. It is a command that tells Selenium IDE which GUI elements like – Text Box, Buttons, Check Boxes etc, it needs to operate on. Finding correct GUI elements is a prerequisite for creating an automation script but, accurate identification of GUI elements is much more difficult than it sounds. Sometimes, you might even end up working with incorrect GUI elements or no elements at all! Hence, using the right locator ensures that the tests are faster, more reliable or has lower maintenance over releases.
Having understood this, let’s dive deeper and understand the various types of locators in Selenium.
Types of Locators in Selenium
There is a diverse range of web elements like text box, id, radio button etc. It requires an effective and accurate approach to identify these elements. Thereby, you can assert that with an increase in effectiveness of locator, the stability of the automation script will increase. Alternatively, you can check out the Automation Course by Edureka and get certified!
- Id locator
- Name locator
- linkText & Partial linkText
- CSS Selector
- XPath
Id Locator
The most popular way to identify web element is to use Id. Id’s are considered as the safest and fastest locator option and should always be the first choice even when there are multiple choices. For example – the employee Number or Account which will be unique.
Now, let’s understand the working of ID locator with the help of an example. I will launch Google Chrome and navigate to yahoo.com. Here, I will try to locate the email text box using ID Locator.
On inspecting the above web element, you can see it has an input tag and attributes like class and id. Now, I will use the value of Id locator i.e. login-username to locate the email text box.
Let’s see how to automate the text box and send values to it using Id locator.
package Edureka; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class Locators { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:Selenium-java-edurekachromedriver_win32chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get("https://login.yahoo.com/"); driver.findElement(By.id("login-username")).sendKeys("edureka@yahoo.com"); //id locator for text box WebElement searchIcon = driver.findElement(By.id("login-signin"));//id locator for next button searchIcon.click(); }
When you run the above Java program, chrome driver will launch Google Chrome, redirect to yahoo mail, enter the email address and navigate to next page. You can refer below image for the output:
I hope this gives you a clear understanding of how Id locator in Selenium works. Now let’s move further and understand how to use name locator.
Name locator
This is also an effective way to locate an element with a name attribute. With this strategy, the first element with the value of the name attribute will be returned. If no element has a matching name attribute, then a NoSuchElementException will be raised.
Now, let’s see the working of name locator with the help of an example. In the below image you can see, the name locator possesses a value called username. The difference here is that you should use a name instead of id.
Let’s take a look at the below code to automate the text box.
driver.get("https://login.yahoo.com/"); driver.findElement(By.name("username")).sendKeys("edureka@yahoo.com"); //name locator for text box WebElement searchIcon = driver.findElement(By.name("signin"));//name locator for next button searchIcon.click();
When you run the above Java code, your output will be the same as Id locator. Now, let’s understand one more locator i.e. linkText.
linkText
You can identify the hyperlinks on a web page using linkText. It can be determined with the help of an anchor tag (<a>). In order to create the hyperlinks on a web page, you can use anchor tags followed by the linkText.
Now, let’s see the working of the linkText locator with the help of an example. Suppose you want to locate ‘Trouble Signing in?‘ link as shown in the below figure. How will you do that?
Let me take you through the steps.
On inspecting “Trouble signing in?” – you can notice that it starts with an anchor tag. But, this anchor tag doesn’t have any name and Id attributes. In such cases, you can use linkText locator.
As you can see in the above snippet, it has a text called “Trouble Signing in?”. I will make use of that text and use a linkText locator to write my code as shown below.
driver.get("https://login.yahoo.com/"); driver.findElement(By.linkText("Trouble Signing in?")).click();//linkText locator for links
In some situations, you may need to find links by a portion of the text in a linkText element. In such situations, you can use Partial Link Text to locate elements. Let’s take the same example and try to locate it. I will choose “Trouble signing in?” link. Now, instead of pasting full text I will just give it as Trouble. So I will modify my code like this –
driver.get("https://login.yahoo.com/"); driver.findElement(By.partiallinkText("Trouble")).click();//partiallinkText locator for links
Now, when you run the above code, it will be redirected to “Trouble Signing In?” page, but the difference is that you are using partial value to locate the links. I hope this gives you a clear understanding of how linkText and partialLinkText locator in selenium works. Now let’s move further and understand one of the simplest locators in selenium.
CSS Selectors
The CSS is mainly used to provide style rules for the web pages and you can use it for identifying one or more elements in the web page. The CSS selector is always the best possible way to locate complex elements in the page.
driver.findElement(By.cssSelector("#login-username")).sendKeys("edureka@yahoo.com"); driver.findElement(By.cssSelector("#login-signin")).click();
When you run the above piece of code, you will be redirected to Yahoo Login page and it asks you to enter the password. That’s how it works. Now let’s dive into the last locator of this article and understand XPath.
XPath
XPath is a language to query XML documents. XPath is an important strategy to locate elements in selenium. It also consists of a path expression along with some conditions. Here, you can easily write an XPath script/query to locate any element in the webpage.
Now, let’s try understanding this with the help of an example. I will start Google Chrome and navigate to google.com. Here, I will try to locate the search box using XPath. On inspecting the web element you can see it has an input tag and attributes like class and id. Next, I will make use of tag name and these attributes to construct XPath which in turn will locate the search bar.
You just need to click Elements tab and press Ctrl + F to open a search box in Chrome’s developer’s tool. Here, you can write XPath, string selector and it gives the search based on that criteria.
In the above image, you can see that it has an input tag. Now, I will start with // input. Here //input implies a tag name. I will make use of the name attribute and pass ‘q’ in single quotes as its value. This will give the below XPath expression:
//input[@name=’q’]
In the above image, you can see that on writing the XPath it has highlighted the element which implies that this particular element was located using XPath.
Now, you can use the below code in your Eclipse to locate a particular element using XPath.
driver.get("https://www.google.com/"); driver.findElement(By.xpath("//input[@id='q']")).sendKeys("Selenium"); //xpath for search box WebElement searchIcon = driver.findElement(By.xpath("//input[@id='Google Search']"));//xpath for search button
Selenium Locators Best Practices
Understanding the concept of locators in Selenium is one thing, but knowing how to use them is quite another. Being able to build a robust locator begins with an understanding of what a robust locator is. Here are three below listed criteria that you must adhere to while using locators in selenium:
- Robust locators in Selenium are as simple and small as possible: The more elements a locator contains, the higher the chances it’ll break because of the change in the page structure.
- Selenium locators still work after you change the properties of a UI element: Relying on frequently-changed attributes like modifier classes (menu__item–red) is never a good practice.
- Selenium locators that are robust in nature still work after you change the UI elements around the element you target: Whenever you use a non-unique attribute, there are chances that locators will break because someone added an element with that same attribute above.
Find out our Selenium Training in Top Cities/Countries
India | Other Cities/Countries |
Bangalore | US |
Hyderabad | UK |
Pune | Canada |
Chennai | Australia |
Mumbai | Singapore |
Kolkata | Edinburgh |
This brings us to the end of this article on Locators in Selenium. I hope it helped you and added value to your knowledge.
If you wish to learn Selenium and build a career in the testing domain, then check out our interactive, live-online Selenium Course, which comes with 24*7 support to guide you throughout your learning period.
Got a question for us? Please mention it in the comments section of Locators in Selenium article, and we will get back to you.