Back to Top

Element Locators In Selenium WebDriver

Updated 8 September 2017

In the previous blog we learnt how to configure Eclipse with selenium and to create an environment where we can start write some script.
Consider we are writing a selenium script to open a website (say webkul.com). Now, how to verify if the page opened at the execution is of webkul itself. Is it the same page we were looking for? To achieve this, we need to find some elements in page which verifies that it is correct. We have different element locators in selenium to locate elements and perform actions like – click, type, select etc. So, knowledge of element locators is necessary to work with selenium.
Below are the locators which are supported by selenium :

  1. By ID
  2. By Name
  3. By Class Name
  4. By Tag Name
  5. By Link Text Or Partial Link Text
  6. By cssSelector
  7. By XPath

Locating Element By ID

If a web application page has an element with unique and a static Id, we can locate that element by it’s Id. For example, In the below image we have a search input with it’s id as “search”. Here, we will get the element by its id and will write a keyword which we wanted to search.

Driver.findElementBy.Id(“search”).sendkeys(“Marketplace for shopify”);

Below example will show how to get element by it’s id and send some keys to that element:

package elementById;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByID {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  // setting the driver executable for chrome browser
		driver = new ChromeDriver();				// created a new instance for chrome driver
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementById() 
			throws InterruptedException
	{
		driver.navigate().to("http://store.webkul.com");
		Thread.sleep(1000);
		driver.findElement(By.id("search")).sendKeys("MarketPlace for shopify");
	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

Locating Element By Name

When we locate an element by it’s name, the web driver looks for name attribute specified by us. Finding an element by “ID” or by “Name” is same. The only difference is, for ID web driver looks element with specified ID and incase of Name it search for specified name.
In the above example we found element by id. Lets get the same element via its attribute name instead of ID.
Driver.findElementBy.Name(“q”).sendkeys(“Marketplace for shopify”);

Start your headless eCommerce
now.
Find out More

 

package elementByName;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByName {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  // setting the driver executable for chrome browser
		driver = new ChromeDriver();				// created a new instance for chrome driver
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementByName() 
			throws InterruptedException
	{
		driver.navigate().to("http://store.webkul.com");
		Thread.sleep(1000);
		driver.findElement(By.name("q")).sendKeys("MarketPlace for shopify");
	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

Locating Element By Class Name

We have seen how to locate elements by IDs and Name. But, what if an element neither has an ID nor a Name in its attribute? So, locating an element by its class name is a good choice when we don’t have a ID or name to locate with.

Driver.findElementBy.ClassName(“logo”);

 

In the above image, we don’t have any Id or name to locate the logo which contains “Webkul Store”. Here, we can see that the element has a class associated “logo”. We can use this class to get the text inside this element. Lets see the code below:

package elementByClassName;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByClassNme {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  
		driver = new ChromeDriver();				
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementByClassName() 
			throws InterruptedException
	{
		driver.navigate().to("http://store.webkul.com");
		Thread.sleep(1000);
		String logoText= driver.findElement(By.className("logo")).getText();
		if(logoText.equalsIgnoreCase("webkul store"))
		{
			System.out.println("We are at the home page of webkul store");
		}else
			System.out.println("We are not at the home page of webkul store");
	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

Locating Element By Tag Name

Till now, we have located elements using ID,Name and Class Name. Considering, if an element don’t have an Id, Class and Name attribute. Here, we have another selector in selenium which looks for element’s tag name in the web page.
Although, their are other selectors like xpath or css selector to look for elements with no id or name. We can also use tag name to find elements. This strategy is not much popular because in a web page there are many elements with same tag name. So, it would be difficult to get the tag we are looking for (a page could have hundreds of elements with same tag).
In the below image we have to click on drop-down to select the currency for the website.To get this we can use the tag name selector, perhaps, we can get this element by Id :

driver.findElement(By.tagName(“select”))

 

The practical implementation foe selecting element by tag name is given below:

package elementByTagName;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByTagName {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  
		driver = new ChromeDriver();				
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementByTagName() 
			throws InterruptedException
	{
		driver.navigate().to("http://store.webkul.com");
		Thread.sleep(1000);
		String SupportedCurrenry= driver.findElement(By.tagName("select")).getText();
		System.out.println("The currencies supported by webkul are :\n "+ SupportedCurrenry);
	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

Suppose, we want to target a link and if you know the text under link area, the best selector we can use is By link text or By partial link text.
If we are using Link text, we need to specify the full text and if we don’t know the full link text then, we can use a part of link via partial link text.
In the below image we have a link text as ”we’re hiring “. Now, we will see the implementation by Link-text as well as by Partial-link text.

driver.findElement(By.linkText(“we’re hiring”));
driver.findElement(By.partialLinkText(“we’re”));

Below is the implementation for using element by Link or partial link:

package elementByLinkText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByLinkText {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  
		driver = new ChromeDriver();				
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementByLinkText() 
			throws InterruptedException
	{
		driver.navigate().to("http://webkul.com");
		Thread.sleep(1000);
		driver.findElement(By.linkText("we’re hiring")).click(); // we can use any "linkText" or "PartialLinkText"
//		driver.findElement(By.partialLinkText("we’re")).click(); 
	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

Locating Element by Css Selector

CSS is “Cascading Style Sheets”, defined to display HTML in structured styles at the webpage. It is a combination of element selectors and selector value which identifies the element. If we don’t have an option to select an element via Id or class, we can use css selector.

Consider the first element (the search box), we located the input by Id. Now, lets see how can we do the same using Css Selector:
driver.findElement(By.cssSelector(“input[name=’q’]”));

 

package elementByCssSelector;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByCssSelector {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  
		driver = new ChromeDriver();				
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementByCssSelector() 
			throws InterruptedException
	{
		driver.navigate().to("http://webkul.com");
		Thread.sleep(1000);
		driver.findElement(By.cssSelector("input[name='q']")).sendKeys("Marketplace for shopify");;

	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

Locating Element By Xpath

XPath is defined as XML path. We can find any element on the web page using XML path expression of that particular element. It is most popular and best way to locate element in WebDriver.
Below is a basic syntax of xpath experssion :
xpath=//tagname[@attribute=’value’] , where

  • // : Select node. (we use * to define anywhere(node) at the page)
  • Tagname: Tagname of the particular node/element.
  • @: Select attribute.
  • Attribute: Attribute name of the node. (eg: id, name, class)
  • Value: Value of the attribute (eg: id= “id1” , name= “fname”)

Lets write an xpath of an input element which have id=”search” in the whole page. It will be like
driver.findElement(By.xpath(“//input[@id=’search’]”));

package elementByCssXpath;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FindElementByXpath {
	WebDriver driver;
	@BeforeTest
	public void setUp() throws Exception {
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";  
		driver = new ChromeDriver();				
		driver.manage().window().maximize(); 
	}
	@Test
	public void findElementByXpath() 
			throws InterruptedException
	{
		driver.navigate().to("http://store.webkul.com");
		Thread.sleep(1000);
		driver.findElement(By.xpath("//*[@id='search']")).sendKeys("Marketplace for shopify");

	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}
}

 

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • Rahul22sep
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content