Working with Selenium WebElements

Table of Contents

In our previous tutorial, Getting Started with Selenium WebDriver, we discussed the way to set up the environment for automating testing using Selenium and wrote a basic script to do a simple test. In this tutorial, we will discuss other functionalities of the Selenium Web Driver in depth with examples.

1. Selenium WebElements

Web Element is a class in Web Driver to handle different  HTML elements of a web page. It can locate and perform different functionalities upon them. Following are the two methods, commonly used to obtain AUT elements directly and to store them as WebElement objects.

 

  • findElement() – It returns a single WebElement
  • findElements() – It returns a list of WebElements.
 

In order to create objects of WebElement, we need to import the package Selenium.WebElement

import org.openqa.selenium.WebElement;

2. WebElement Locators

Locating different web elements are extremely crucial in testing web pages since the chance of ending up with incorrect elements is higher. Therefore, Selenium WebElement has introduced several different ”Locators” to locate web elements using their unique properties precisely. They can be easily identified using the Selenium IDE or Browser’s Developer Tool. Below is a list of Locators and their syntaxes.

Locator Syntax Description
ID driver.findElement(By.id(“<ID_OF_THE_ELEMENT>”)  Finds element using ID attribute.
name driver.findElement(By.name(“<NAME_OF_THE_ELEMENT>”)  Finds element using name attribute
className driver.findElement(By.className(“<CLASS_NAME_OF_THE_ELEMENT>”)  Finds element using their class
linkText driver.findElement(By.linkText(“<TEXT_IN_THE_LINK>”)  Finds element using text in the link
partialLinkText driver.findElement(By.partialLinkText(“<PARTIAL_TEXT_IN_THE_LINK>”)  Finds element using part of the text in the link
xpath driver.findElement(By.xpath(“<xpath_OF_THE_ELEMENT>”)  Finds element using xpath attribute
cssSelector driver.findElement(By.cssSelector(“<cssSelector_OF_THE_ELEMENT>”)  Finds element using css selector
tagName driver.findElement(By.id(“<tagName_OF_THE_ELEMENT>”)  Finds element using name of their tag

Once the elements are located, different functionalities can be performed on them. In this tutorial, we will be using a sample web form to explain how Selenium WebElements can be used to test its various form elements.

3. Working With Text Box

Initially, we need to create WebElements for the ‘Firstname’ and ‘Lastname’ fields.blank

Note that the “firstname” is located by the “name” attribute, and the “lastname” is located by the “id” attribute.

Once the element objects are made, the first thing to do is to clear the text, which is already in the text field. This is done by the clear() method.

blank

Finally, we can enter the relevant text using the sendKeys() method by sending the text value as the parameter.

4. Working With Buttons

Buttons are usually accessed through the click() method. In the case of Submit buttons, the submit() method will be used to submit all the inputs to the server.

blank

In this case, the className is used as the locator to find the button.

5. Checkboxes and Radio Buttons

Toggling checkboxes on or off and selecting radio buttons are done using the click() method.

blank

The checkbox element is located using its XPath. This code checks if the checkbox is selected or not and then prints a message.

In the case of Radio Buttons, it is located using cssSelector.

blank

6. Selecting from Drop-Downs

Before selecting values from a drop-down, we need to import a package.

import org.openqa.selenium.support.ui.Select;

Once that is done, we can declare the drop-down as a Select object.

Now we can control the drop-down by selecting its values using different methods defined in the Select class.

blank

We can repeat the above code with different parameters when selecting multiple items.

blank

7. File Uploads

There are a couple of solutions available for implementing ‘File Upload’ functionality within your selenium scripts. However, not all solutions may work on all applications because at times it may depend on typical ‘design or kind of implementation’ your application or website uses at the backend and/or client end.

However here is one such, simple implementation for File uploading. In the below snippet ‘File Uploading’ is simply done by locating the file-select input field and by entering the path of the file to be uploaded using the sendKeys() method.

blank

8. Locating Links

We can locate links and access them using the linkText() and partialLinkText() locators. In the below example, we will obtain the link with its complete text using linkText() and part of the link text using partialLinkText() locator.

blank
blank

Here is the complete code.

package newPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myClass {

   public static void main(String[]args) throws InterruptedException{
      System.setProperty("webdriver.gecko.driver", "C:\\geckodriver\\geckodriver.exe");
      
      WebDriver driver = new FirefoxDriver();
      
      String baseUrl = "https://www.toolsqa.com/automation-practice-form/";
        String pageTitle="";
      driver.get(baseUrl);
      
      //Clicking a link text using linkText Locator
      driver.findElement(By.linkText("Partial Link Test")).click();
      System.out.println(driver.getTitle());
      Thread.sleep(1000);
      
      //Clicking a link text using partialLinkText Locator
      driver.findElement(By.partialLinkText("Partial")).click();
      System.out.println(driver.getTitle());
      
      //Capturing the page title
      pageTitle = driver.getTitle();
      
      //Get webElements for First name and Last name text boxes
      //Locator by name
      WebElement firstName= driver.findElement(By.name("firstname"));
      //Locator by Id
      WebElement lastName= driver.findElement(By.id("lastname"));
      
      //Clearing the text fields
      firstName.clear();
      lastName.clear();
      
      //Entering values to the text field
      firstName.sendKeys("John");
      lastName.sendKeys("Doe");
      
      //Get webElements for gender radio buttons using cssSelector
      WebElement radioMale=driver.findElement(By.cssSelector("input#sex-0"));
      //Selecting it using click()method and printing their values.
      radioMale.click();
      System.out.println("Male Selected");
      
      WebElement radioFmale=driver.findElement(By.cssSelector("input#sex-1"));
      radioFmale.click();
      System.out.println("Female Selected");
      
      //Selecting years of experience radio button
      WebElement yrsExp= driver.findElement(By.id("exp-2"));
      yrsExp.click();
      //Printing the number of experience selected
      System.out.println("Years of Experience = " + yrsExp.getText());
      
      //Entering values in Date text box
      WebElement date= driver.findElement(By.id("datepicker"));
      date.sendKeys("17-12-2019");
      
      //Selecting Profession Check box
      WebElement prof= driver.findElement(By.id("profession-0"));
      prof.click();
      
      //uploading a file
      WebElement uploadElement = driver.findElement(By.id("photo"));
      uploadElement.sendKeys("C:\\profilePic.jpg");
      
      //Creating web element for selecting Automation tool using xpath
      WebElement selQtp= driver.findElement(By.xpath("//*[@id=\'tool-0']"));
      // Toggling on and off to see if selected
      selQtp.click();	
      
      if (selQtp.isSelected())
         System.out.println("QTP Selected");
      else
         System.out.println("QTP Not Selected");
      //Unchecking
      selQtp.click();	
      
      if (!selQtp.isSelected())
         System.out.println("QTP Not Selected");
      
      //Selecting single continent using drop down
      Select singleContiDrp = new Select(driver.findElement(By.id("continents")));
      
      singleContiDrp.deselectByVisibleText("South America");
      
      //Selecting multiple continent using drop down
      Select contiDrp = new Select(driver.findElement(By.id("continentsmultiple")));
      
      contiDrp.deselectByVisibleText("Asia");
      contiDrp.deselectByVisibleText("Europe");
      
      //Locating button using className
      WebElement firstBtn= driver.findElement(By.className("btn btn-info"));
      firstBtn.click();
   
      
      Thread.sleep(1000);
      if (pageTitle.contentEquals(driver.getTitle())){
         System.out.println("Test Passed!");

         } else {

         System.out.println("Test Failed");}	 
      driver.close();
      
   }
   
}

9. Summary

  • Selenium web driver captures different form elements using Selenium WebElements.
  • WebElement uses different properties like ID, name, className, cssSelector, link text, and xpath of the form elements to locate them using the findElement() method.
  • The sendKey() method is used to enter values to the text field, and a clear() method is used to delete values in the text field.
  • Buttons, Radio buttons, and Checkboxes can be clicked using the Click() method.
  • Dropdowns should be instantiated as an object of the ‘Select’ class to control them within a Selenium script.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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

SELENIUM TUTORIALS

Recent Posts

RELATED POSTS

Getting Started with Apache JMeter

1. Introduction As a developer, you may have tested the functionality of your code hundreds of times during development. This is known as functional testing....

VBS Part 2 – Fundamentals and Concepts

Having gone through the Introductory part, it is time to look at some crucial fundamentals and concepts. This article is to refresh some of...

Automation Tools Comparison (SilkTest vs QTP vs Selenium)

While manual testing and automated testing go hand in hand, one of the important benefits of automated testing is the assurance that the software...

How To Use TestNG with Selenium

1. What is TestNG? TestNG is an open-source automated testing framework with flexible and powerful features. It is inspired by JUnit and NUnit but with...

Â

CHECKOUT 'HOW-TOs'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string...

MORE ON CODEX

MORE IN THIS CATEGORY

Java Tutorial #4 – Control Statements

Introduction Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of...

How To Do API Testing with JMeter

Introduction Application Programming Interface is a very popular term among developers. It is simply a request provider that responds to your request. In other words,...

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...

How To Do Database Testing with JMeter

Introduction In this 'How-To', You will be guided to perform a database load test using JMeter. We will be installing Apache JMeter to perform the...

OTHER TUTORIALS

Format Decimal Numbers with Grouping Separator

The DecimalFormat class has a method called setGroupingSize() which sets how many digits of the integer part to group....

Working with JMeter Listeners

- Advertisement -spot_img