9j. WebDriver – Locating elements: Part 1 (by id, name, tagName)

Hiya friends! If you stepped into the World of Selenium, you must have run into Web Elements! Text boxes, buttons, links, checkboxes, radio buttons, dropdowns, alerts etc., everything is treated as a web element. Using locator types and strategies, we can easily identify any desired element on the page. This is the most crucial step for interacting with the page and referencing these elements further in the code. And yes, it is very similar to what we saw in Selenium IDE except for the syntax and the way the concept is applied.

General syntax for locating a web element using Selenium webDriver is,

driver.findElement(By.LocatorStrategyType ("Locator_Value"));

Explanation:

  • driver – instance variable for the corresponding driver class that implements WebDriver interface
  • findElement() – finds and returns the first web element with the specified location strategy
  • findElements() – finds and returns a list of web elements matching the given location strategy
  • By – target is always located using By class
  • LocatorStrategyType – id, name, tagName, className, cssSelector, linkText, partialLinkText, xpath are some of the locator types available for locating elements on the page
  • Locator_Value – The value/HTML tag with which the element can be identified

Available locator types are,

  • Id
  • Name
  • tagName
  • className
  • linkText
  • partialLinkText
  • cssSelector
  • xPath

It is possible at all times to get hold of the desired element on the page programmatically but in order to achieve it, our creative side might have to take a peek. Reason, we don’t always have control over the HTML on the page. That’s why we have so many locator types and there is absolutely no reason to panic!

Let us go ahead and see each locator type in detail with code examples.

Locating by id

Id is the most useful and preferred way to locate an element on the page because it is unique. But, watch out! Some developers either auto-generate these ids or totally forget to include one. That is when we go for other locator types.

Syntax: driver.findElement(By.id(“element_id”));

Explanation: Locates the first element with the matching id attribute.

Example: Open Google Account creation page. Let us identify the first name text box by Id.

  • Google Chrome – Right click on the web element whose ID is to be determined and select ‘Inspect’. Or open developer tools by clicking F12, click inspect element icon on the top left corner and then click on the desired web element on the page. Both methods will highlight the HTML code corresponding to the chosen element.
  • Mozilla Firefox – Right click on the web element and select ‘Inspect element with Firebug’ (In case you missed my post on Firebug installation and usage). Or just right-click on the element and select ‘Inspect element’ if you don’t really want to use Firebug. Corresponding HTML code will be opened and highlighted in both cases.

Locating by Id

As shown in the above screenshot, id of the First Name text box is ‘FirstName’. Hence the code to be used here is,

driver.findElement(By.id("FirstName"));

Locating by name

Name attribute can also be used to locate an element on the page.

Syntax: driver.findElement(By.name(“element_name”));

Explanation: Locates the first element with the matching name attribute.

Example: Let us identify the last name text box by name.

Right click on the last name text box and click on inspect element to get the corresponding HTML code. The name attribute in our case has the value, LastName. Hence the code to locate this web element by name would be,

driver.findElement(By.name("LastName"));

Locating by Name

Locating by tagName

Here we use the actual name of the tag like <a> for anchor and <table> for table. This turns out to be useful when we would like to get all the elements with a given tag name. In case the page under test has only one tag then findElement would work. But otherwise, it is adviced to index the result to locate the specific element we wish to work with.

Syntax: driver.findElements(By.tagName(“element_html_tag”));

Explanation: Locates all the elements with the matching tag name.

Example: Let us locate the ‘Sign in’ button on the top right corner of the Gmail account creation page.

Right click on the button and click on inspect element to get the corresponding HTML code. We can see that it has an anchor tag. Let us go ahead and get all the web elements with the tagName “a” in a list and then locate the first element by its index in order to interact with ‘Sign in’ button.

// List of all elements with anchor tag
List<WebElement> buttons = driver.findElements(By.tagName("a"));
// Locate 'Sign in' button by indexing the list
WebElement signInButton = buttons.get(0);

Overall picture

To avoid any unexpected surprises that you may encounter while trying out these locators, let us see a test case implementing the above locator types.

Scenario

  1. Open Firefox browser.
  2. Navigate to google account creation page
  3. Locate first name text box by id
  4. Enter ‘fname01’ as the first name
  5. Locate last name text box by name
  6. Enter ‘lname01’ as the last name
  7. Locate ‘Sign in’ button with tagName
  8. Print the button text to console for verification

JUnit code for this scenario is,

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ElementLocatorTest1 {
	//Declaring variables
	private WebDriver driver; 
	private String baseUrl;

	@Before
	public void setUp() throws Exception{
		// Selenium version 3 beta releases require system property set up
		System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
				+ "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
		// Create a new instance for the class FirefoxDriver
		// that implements WebDriver interface
		driver = new FirefoxDriver();
		// Implicit wait for 5 seconds
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		// Assign the URL to be invoked to a String variable
		baseUrl = "https://accounts.google.com/SignUp";
	}
	
	@Test
	public void testPageTitle() throws Exception{
		// Open baseUrl in Firefox browser window
		driver.get(baseUrl);
		// Locate First Name text box by id and
		// assign it to a variable of type WebElement
		WebElement firstName = driver.findElement(By.id("FirstName"));
		// Clear the default placeholder or any value present
		firstName.clear();
		// Enter/type the value to the text box
		firstName.sendKeys("fname01");
		// Locate last name text box by name
		WebElement lastName = driver.findElement(By.name("LastName"));
		// Clear and enter a value
		lastName.clear();
		lastName.sendKeys("lname01");
		// List of all elements with anchor tag
		List<WebElement> buttons = driver.findElements(By.tagName("a"));
		// Locate 'Sign in' button by indexing the list
		WebElement signInButton = buttons.get(0);
		
		// Verifying if the button is located
System.out.println("First button text: " + signInButton.getText());
	}
	
	 @After
	  public void tearDown() throws Exception{
		// Close the Firefox browser
		driver.close();
	}
}

Explanation

Two new packages are to be imported,

import org.openqa.selenium.WebElement – to instantiate a new web element.

import org.openqa.selenium.By; – This package references to the By class on which a locator type is called.

The comments are clearly provided for each line of code and hence self-explanatory.

Output1

Upon executing the test case, success is shown in green and the output is printed to the console confirming that the ‘Sign in’ button is located with tagName. The right half of the image shows the automated output executed in Firefox browser. First name and last name text boxes are filled with the values given in the code.

Let us take a break here. In our following post, we will see three more ways to locate elements with examples. Munch on these thoughts until then!

Have a nice day!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.