Different ways to identify element using Selenium WebDriver’s findElement method


We learned in “Locators In Selenium IDE” chapter and looked by example how to use this locator in the Selenium IDE with examples. To use the same locator in Selenium Webdriver the general syntax is below.

driver.findElement(By.<locatorName> ("<<Identifier>>"));

Element location Strategy:

The findElement methods take a locator value or it query object called ‘By’. In the Eclipse code window after typing driver.findElement(By dot), Eclipse intelligence will populate the list of different locators. ‘By’ strategies like below

eclipse-findElement-By-list
eclipse-findElement-By-list

So, let’s use different locator’s using a findElement method.

  1. By ID: This is the most common way of finding the WebElementSyntax
    driver.findElement(By.id(“Element ID”));

     

    If no element has a matching id attribute, then NoSuchElementException will be raised.

    Actual Command example:

    WebElement element = driver.findElement(By.id("submit"));
    // Action can be performed on Input Button element
    element.submit();
    

     

  2. By Name: This is also a unique way of locating an element as per standard web page design UI developer mostly specify unique “name” for the critical web element in the web page.Syntax:
    driver.findElement(By.name(“Element NAME”));

     

    If no matching element is found then we get “NoSuchElementException”

    Example:

    WebElement element = driver.findElement(By.name("firstname"));
    // Action can be performed on Input Text element
    element.sendKeys("hemant");
    

     

  3. By ClassName: It finds an element based on the value of the class attributes.Syntax:
    driver.findElement(By.className(“Element classname”));

     

    Example:

    	WebElement parentElement = driver.findElement(By.className("button"));
    	WebElement childElement = parentElement.findElement(By.id("submit"));
    	childElement.submit();
    

     

    Tip: To use this method try to locate the element with “ID” attribute within the class HTML tag and use its value.

  4. By TagName: By using this you can find the element by their Tagname.Syntax:
    driver.findElement(By.tagName(“Element TAGNAME”));

     

    This is not one of the most popular methods of locating an element as by using other locators it will be easy to locate the WebElement.

    Example:

    Suppose you want to locate the “Submit” button and you check in the HTML page that Tagname “Button” is present then it can be used to perform an action.

    WebElement element = driver.findElement(By.tagName("button"));
    // Action can be performed on Input Button element
    element.submit();
    

     

  5. By LinkText & PartialLinkText: By Link text: Using this you can find the elements of “a” tags(Link) with the link names associated with it.
    By partial link text: Using this you can find the elements of “a” tags(Link) with the partial link names associated with it.Note: The prerequisite to use “By Link text” or “By partial link text” that the locator should be in the form of the link.Example:

    	WebElement element = driver.findElement(By.linkText("Partial Link Test"));
    	element.clear();
    
    	//Or can be identified as 
    	WebElement element = driver.findElement(By.partialLinkText("Partial");
    	element.clear();
    

     

  6. By XPath: For me, It’s a most popular and majorly used element locating. XPath takes a parameter of String which is an XPATHEXPRESSION and returns a BY object to findElement() method.Syntax:
    driver.findElement(By.xpath(“Element XPATHEXPRESSION”));

    We have a complete chapter on XPath Techniques in future which we will come across during our learning journey

PracticeExample:

We’ll use Gmail and see how most of these “Find Element” commands are used.

Example steps:

  1. Launch and navigate to https://accounts.google.com/ServiceLogin?sacu=1&rip=1#identifier
  2. Get the title of the page
  3. Check the expected title with actual one
  4. Enter username:” [email protected]
  5. Click on next button
  6. Enter password: “Test@1234”
  7. Click next
  8. Verify whether the login is successful.
  9. Close the browser

Code:

package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.*;


import java.util.concurrent.TimeUnit;

public class FirstTestCase {

	public static void main(String[] args) throws InterruptedException {
		  //if You are using the latest version of Selenium WebDriver i.e. Selenium 3.x, this version of webdriver doesn't support direct Firefox launch. 
		//You have to set the SystemProperty for webdriver.gecko.driver.
		
		DesiredCapabilities capabilities = DesiredCapabilities.firefox();
		capabilities.setCapability("marionette", false);
		WebDriver driver = new FirefoxDriver(capabilities);
		
		

			
		  
			//WebDriver driver;
			//System.setProperty("webdriver.gecko.driver", "geckodriver-v0.18.0-win64\\geckodriver.exe");
			//System.setProperty("webdriver.firefox.marionette", "geckodriver-v0.10.0-win64\\geckodriver.exe");
			// driver =new FirefoxDriver();
				
				
		        String baseUrl = "https://accounts.google.com/ServiceLogin?sacu=1&rip=1#identifier";
		        String expectedTitle = "Sign in - Google Accounts";
		        String actualTitle = "";
		        String expectedText ="Welcome, hemant varhekar";
		        String actualText = "";
		        		

		        // launch Firefox and direct it to the Base URL
		        driver.get(baseUrl);

		        // get the actual value of the title
		        actualTitle = driver.getTitle();
		        System.out.println(actualTitle);

		        /*
		         * compare the actual title of the page witht the expected one and print
		         * the result as "Passed" or "Failed"
		         */
		        if (actualTitle.contentEquals(expectedTitle)){
		            System.out.println("Title matched proceeding for next action!");
		            //•	Enter Username:"[email protected]"
		            	driver.findElement(By.id("identifierId")).sendKeys("[email protected]");
		         
		            //Click on next button 
		            	driver.findElement(By.xpath("//*[@id='identifierNext']/content/span")).click();
		            	Thread.sleep(2000);
		            	WebElement txtbox_password = driver.findElement(By.name("password"));
		            		 
		            		if(txtbox_password.isEnabled())
		            			{
		            			txtbox_password.sendKeys("Test@1234");
		            			}
		           
		            //Click on next button
		            		driver.findElement(By.xpath("//*[@id='passwordNext']/content/span")).click();
		            
		            //wait some time till the page load
		            		Thread.sleep(1000);
		            		actualText= driver.getPageSource();
		           
		            		if (actualText.contains("Welcome"))
		            			{
		            				System.out.println("We have sucessfully logged in!");
		            			}
		            		else
		            		{
		            			System.out.println("Login is unsuccessful");
		            		}
		            
		            
		            
		            
		        } else {
		            System.out.println("Test Failed");
		        }
		       
		        //close Firefox
		       driver.quit();
		

			}

	}

 


Leave a Reply