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....

Getting Started with Selenium WebDriver

Table of Contents 1. Selenium and Selenium Web Driver 2. Setting-Up the Environment 3. Test Script with Selenium Web Driver 3.1) Creating a project 3.2) Creating...

How To Use Mouse and Keyboard Events with Selenium

In this tutorial, we will discuss how to use mouse click events and keyboard events with Selenium WebDriver. The mouse click and keyboard events...

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...

Â

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

HP Borland’s Silk Test for Multi-Channel Testing

The growing web and mobile applications have posed several challenges for software QA teams. While usability and scalability are highly prioritized, compatibility across multiple...

Traditional Framework Definitions (QTP)

Over the years Functional Test Automation has come a long way from WinRunner to QTP and until ALM. The tools have evolved to a...

Review of Test Design Studio 2.0

While QTP offers greater flexibility to automate testing procedures, the IDE lacks certain professional features. A QTP license is expensive as well. Test Design...

Introducing Testing-as-a-Service (TaaS)

The 'Cloud Computing' technology has revolutionized the IT industry and it has something good to offer to the testing industry too. After Iaas, PaaS,...

OTHER TUTORIALS

Basic PowerShell Commands That You Should Know

One of the key benefits of PowerShell is its object-oriented nature. Instead of working with text-based output like traditional...
- Advertisement -spot_img