Home  >  Blog  >   Selenium

Using Selenium to Interact With Elements on a Web Page

Rating: 5
  
 
7751
  1. Share:
Selenium Articles

A web application runs in servers where most of the complex processing takes place: interactions with databases and external services, validation of business logic, and encryption and security measures. The user does not need to know the details of how the application is being executed in the background. A web application consists of many elements that a user can interact with.

'For the user/web application interaction to happen, a web browser is required. The browser presents the user with a frontend that is basically a combination of HTML (Hypertext Markup Language: the one that defines the structure and some behavior of the page), CSS (Cascading Style Sheets: the one that defines the look-and-feel of the page), and JavaScript (the one that allows behavior and interaction beyond HTML capabilities).

 

If you want to become a Selenium Certified Specialist, then visit Mindmajix - A Global online training platform: Online Selenium Training Course”.  This course will help you to achieve excellence in this domain.

Why WebElement in Selenium?

It is useful to be able to review and analyze the code behind a web page in order to understand it and define how to locate and interact with its elements for testing purposes. 

The Selenium WebElement does just that. Its interface allows you to create variables of the WebElement type, which represent HTML elements on a web page, and also provides methods to interact with these elements. Some of these elements include:

  • Textboxes 
  • Textareas
  • Dowpdown 
  • Lists
  • Radio buttons
  • Checkboxes

This article will take you to a Selenium automation script that will be able to simulate interactions with these elements and does so by methods provided by the WebElement class.

Interacting with Textboxes and Textareas Elements

The following are some of the methods provided by the WebElement class to interact with textboxes and textareas elements during the execution of a script:

  • boolean isEnabled(): Indicates if an element is enabled or not.
  • java.lang.String getAttribute(java.lang.String name): Gets the current value of a given attribute of an element. This is very useful for getting the contents of text areas, text boxes, and input elements.
  • java.lang.String getText(): Returns the visible inner text of an element. If the element has sub-elements, it will return a string with no spaces.
  • void sendKeys(java.lang.CharSequence… keysToSend): Simulates typing into an element.
  • boolean isDisplayed(): Indicates if an element is visible or not.

Interacting with Textboxes and Textareas During an Automation Script

The aim here is to create an automation script that interacts with textboxes and textareas. Assume that the textbox/textarea element has been found by means of its ID:

WebElement textArea = driver.findElement(By.
id("aboutYourself"));

Open the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file and use IntelliJ IDEA for the creation of a Selenium script. 

The steps for the completion of this process are as follows:

  • Review and analyze the structure and behavior of the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file.
  • Create a new Java file for the automation script. Make sure that you include the required libraries:
package com.beginningselenium.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
  • Locate the textarea of the By.id "aboutYourself":
WebElement textArea = driver.findElement(By.
id("aboutYourself"));
  • Verify that the textarea is enabled and visible:
if (textArea.isEnabled() && textArea.isDisplayed())
  • Using the System.out.println the method in the if loop, display messages indicating whether the verification was successful or not:
System.out.println("The text area is visible and
displayed");
else {
        System.out.println("Something went wrong, the text
area is not visible and displayed");
     }
  • If the text area is enabled and visible, verify that it is empty:
// Checking for an empty text area
if ("".equals(textArea.getAttribute("value")))
  • Using the System.out.println a the the method, display messages indicating whether the verification was successful or not:
{
        System.out.println("The text area is empty");
    } else {
        System.out.println("Something is wrong, the text
area NOT empty");
    }
  • Input some text and then verify that the text was actually typed:
textArea.sendKeys("This is a sample text.");
if ("This is a sample text.".equals(textArea.
getAttribute("value")))
  • Using the System.out.println method, display messages indicating whether the verification was successful or not and that the name was sent.
{
        System.out.println("Text was correctly typed into
the text area.");
    } else {
        System.out.println("Something went wrong, text
was not typed into the text area.");
    }
  • Clear the textarea contents and verify that it is empty:
textArea.clear();
if ("".equals(textArea.getAttribute("value")))
  • Using the System.out.println a method, display messages indicating whether the verification was successful or not and that the name was sent:
{
        System.out.println("The text area is empty after
cleaning it though a Selenium command");
    } else {
        System.out.println("Something went wrong, the
text area was not cleaned");
    }
  • Compile and run the script.

Also Read: What Is Selenium Testing In Detail Guide

Interacting with Dropdown and Lists

Dropdown and lists elements are manipulated by means of the Select class. This class provides methods and properties to interact with dropdown and lists that are created with the < select > element:

  • void deselectAll(): Clears all selected entries
  • void deselectByIndex(int index): Clears the option at the given index
  • void deselectByValue(java.lang.String value): Clears all options that match a given value
  • void deselectByVisibleText(java.lang.String value): Clears all options that display text matching a given value
  • java.util.List getAllSelectedOptions(): Gets all selected options of the list
  • WebElement getFirstSelectedOption(): Gets the first selected option of the list java.util.List getOptions(): Gets all options of the list
  • boolean isMultiple(): Indicates if the list supports multiple options at the same time or not void selectByIndex(int index): Selects the option at the given index
  • void selectByValue(java.lang.String value): Selects all options that match a given value
  • void selectByVisibleText(java.lang.String text): Selects all options that display text matching a given text

 MindMajix YouTube Channel

The aim here is to create an automation script that interacts with dropdowns and lists. For this example, assume that the dropdown element has been found by means of a combination of the Select method and its ID:

Select list = new Select(driver.findElement(By.
id("monthOfBirth")));

Open the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file and use IntelliJ IDEA for the creation of a Selenium script. The steps for the completion of this process are as follows:

  • Review and analyze the structure and behavior of the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file.
  • Create a new Java file for the automation script. Make sure that you include the required libraries:
package com.beginningselenium.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
First, you’ll work with a single choice list. Locate the dropdown list of By.id "monthOfBirth":

Select singleChoiceList = new Select(driver.findElement(By.id("monthOfBirth")));
If the dropdown is enabled and visible, verify that it does not allow multiple selections and that it contains 13 options (including "Choose…"):

if (!singleChoiceList.isMultiple() && singleChoiceList.
getOptions().size() == 13)
{
}
Using the System.out.println the method, display messages indicating whether the verification was successful or not:

System.out.println("The list does not accept multiple
choices and contains 13 options (including 'Choose...').");
If the list does not allow multiple selections and its size is 13, select the option "February" by sending its value:
if (!singleChoiceList.isMultiple() && singleChoiceList.
getOptions().size() == 13)
{
singleChoiceList.selectByVisibleText("February");
}
You can also select an option by value:

singleChoiceList.selectByValue("february");
Or by index:

singleChoiceList.selectByIndex(2);
Verify that "February" is selected as an option and use the System.out.println the method, which displays messages indicating whether the verification was successful or not and the option chosen:
if (!singleChoiceList.isMultiple() && singleChoiceList.
getOptions().size() == 13)
    {
        singleChoiceList.selectByVisibleText("February");
        if (singleChoiceList.getFirstSelectedOption().
getText().equalsIgnoreCase("February"))
    {
    } else {
    }
}
Now, you’ll work with a multiple-choice list. Locate the dropdown list of By.id "monthOfBirth":

Select multipleChoiceList = new Select(driver.
findElement(By.id("hobbies")));
If the dropdown is enabled and visible, verify that it does allow multiple selections and that it contains four options:
if (multipleChoiceList.isMultiple() && multipleChoiceList.
getOptions().size() == 4)
              {
    }
  • Using the System.out.println the method, display messages indicating whether the verification was successful or not.
System.out.println("The list does accept multiple choicesmand contains 4 options.");
  • If the list does allow multiple selections and its size is 4, select the different options by sending its values:
if (multipleChoiceList.isMultiple() && multipleChoiceList.
getOptions().size() == 4)
{
    multipleChoiceList.selectByVisibleText("Reading");
    multipleChoiceList.selectByVisibleText("Sports");
    multipleChoiceList.selectByVisibleText("Traveling");
}
  • Deselect an option using the value attribute:
multipleChoiceList.deSelectByValue("sports");

You can also deselect an option by its index:

multipleChoiceList.deselectByIndex(0);

Or by its visible text:

multipleChoiceList.deselectByVisibleText("Sports");
  • Verify the number of choices selected and use the method to display messages indicating the number of options chosen:
if (multipleChoiceList.getAllSelectedOptions().size() == 2)
{
    System.out.println("It worked, 2 options have been
chosen");
}
Verify that the two options are actually selected:
List expectedSelection = Arrays.asList("Reading",
"Traveling");
List actualSelection = new ArrayList();
for (WebElement element : multipleChoiceList.
getAllSelectedOptions()) {
    actualSelection.add(element.getText());
}
if (actualSelection.containsAll(expectedSelection)) {
} else {
}
  • Compile and run the script.

 

Selenium Interview Questions

 

Interacting with Radio Buttons and Radio Button Groups

Radio buttons are commonly used in web applications to offer the user a way to select options that are mutually exclusive. WebDriver offers support for radio buttons and radio groups through the WebElement class. Here are some of the methods provided so that you can interact with radio buttons and radio buttons groups elements during the execution of a script:

  • boolean isSelected(): Indicates if an element is selected or not. It applies to input elements such as checkboxes, options in a select button, or a radio button.
  • void click(): Performs a click on an element. It can only be used on visible elements with a width and height bigger than zero (0). If by clicking an element a new page is loaded, all previous references to the element will be invalid.

Interacting with Radio Buttons and Radio Buttons Groups During an Automation Script

The aim is to create an automation script that interacts with radio buttons and radio buttons groups. For this example, assume that the radio button element has been found by means of the findElement method:

WebElement masters = driver.findElement(By.
cssSelector("input[value='masters']"));

Open the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file and use IntelliJ IDEA for the creation of a Selenium script. The steps for the completion of this process are as follows:

  • Review and analyze the structure and behavior of the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file.
  • Create a new Java file for the automation script. Make sure that you include the required libraries.
package com.beginningselenium.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
  • Locate the radio button "Masters":
WebElement masters = driver.findElement(By.
cssSelector("input[value='masters']"));

Note that if you know that the radio button you want to work with belongs to a group, you can locate the group by its name:

List degreeLevel = driver.findElements(By.
name("degree"));
And iterate through its elements:

for (WebElement degree : degreeLevel)
{
  if(degree.getAttribute("value").equals("masters"))
  {
    if(!degree.isSelected()) {
      type.click();
    }
 break;
  }
}
Verify that the radio button "Masters" is enabled and visible:
if (masters.isEnabled() && masters.isDisplayed())
{
}
  • Using the System.out.println the method, display messages indicating whether the verification was successful or not:
System.out.println("The radio button is enabled and visible.");
  • If the radio button is enabled and visible, verify that it is not selected before clicking on it:
if (masters.isEnabled() && masters.isDisplayed())
{
    if (!masters.isSelected())
    {
        masters.click();
    }
}

You can select a radio button by clicking on it after it has been selected.

  • Verify that "Masters" has been selected and use the System.out.println method to display messages, indicating whether the verification was successful or not and the option chosen:
if (masters.isEnabled() && masters.isDisplayed())
{
    if (!masters.isSelected())
    {
       masters.click();
        if (masters.isSelected())
            System.out.println("It worked, the 'Masters'
option was selected");
        else
System.out.println("Something went wrong,
'Masters' was not selected.");
    }
}
  • Compile and run the script.

 

Also ReadLearn the Scope of Automation Testing 

Interacting with Checkboxes

Checkboxes are widely used in web applications, mostly in situations where the user needs to select one or more available options, for example, when selecting user hobbies in a registration form. WebDriver offers support for checkboxes through the WebElement class.

Here are some of the methods provided so that you can interact with checkboxes groups elements during the execution of a script:

  • boolean isSelected(): Indicates if an element is selected or not. It applies to input elements such as checkboxes, options in a select button, or in a radio button.
  • void click(): Performs a click on an element. It can only be used on visible elements with a width and height bigger than zero (0). If by clicking an element a new page is loaded, all previous references to the element will be invalid.

Interacting with Checkboxes During an Automation Script

The aim is to create an automation script that interacts with checkboxes. For this example, assume that the checkbox element has been found by means of the findElement method:

WebElement receiveEmails = driver.findElement(By.
id("emailUpdates"));

Open the

https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file and use IntelliJ

IDEA for the creation of a Selenium script.

  • Review and analyze the structure and behavior of the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file.
  • Create a new Java file for the automation script. Make sure that you include the required libraries.
  • Locate the checkbox "emailUpdates".
WebElement emailUpdates = driver.findElement(By.
id("emailUpdates"))
;
  • Verify that the checkbox is enabled and visible:
if (emailUpdates.isEnabled() && emailUpdates.isDisplayed())
{
}
  • Using the System.out.println the method, display messages indicating whether the verification was successful or not.
  • If the checkbox is enabled and visible, verify that it is not selected before clicking on it:
if (emailUpdates.isEnabled() && emailUpdates.isDisplayed())
{
    if (!emailUpdates.isSelected())
    {
       emailUpdates.click();
    }
}

You can deselect a checkbox by clicking on it after it has been selected.

  • Verify that the checkbox is selected and use the System.out.println method to display messages, indicating whether the verification was successful or not and that the checkbox has been checked:
if (receiveEmails.isEnabled() && receiveEmails.
isDisplayed())
{
    if (!emailUpdates.isSelected())
    {
       emailUpdates.click();
        if (emailUpdates.isSelected())
            System.out.println("Load of the test worked,
checkbox has been selected");
        else
            System.out.println("Something went wrong with
the test, checkbox has not been selected");
    }
}

Now, you have a better understanding how to interact with the elements of a web page.

If you found this article interesting, you can explore Selenium Fundamentals to discover how to use Selenium to efficiently test your own applications. 

Explore Selenium Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!
Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Selenium Training Mar 23 to Apr 07View Details
Selenium Training Mar 26 to Apr 10View Details
Selenium Training Mar 30 to Apr 14View Details
Selenium Training Apr 02 to Apr 17View Details
Last updated: 03 Apr 2023
About Author

 

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

read more
Recommended Courses

1 / 15