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.
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:
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.
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.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:
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;
WebElement textArea = driver.findElement(By.
id("aboutYourself"));
if (textArea.isEnabled() && textArea.isDisplayed())
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");
}
// Checking for an empty text area
if ("".equals(textArea.getAttribute("value")))
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");
}
textArea.sendKeys("This is a sample text.");
if ("This is a sample text.".equals(textArea.
getAttribute("value")))
{
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.");
}
textArea.clear();
if ("".equals(textArea.getAttribute("value")))
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");
}
Also Read: What Is Selenium Testing In Detail Guide
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 entriesvoid deselectByIndex(int index):
Clears the option at the given indexvoid deselectByValue(java.lang.String value):
Clears all options that match a given valuevoid deselectByVisibleText(java.lang.String value):
Clears all options that display text matching a given valuejava.util.List getAllSelectedOptions():
Gets all selected options of the listWebElement getFirstSelectedOption():
Gets the first selected option of the list java.util.List getOptions(): Gets all options of the listboolean isMultiple():
Indicates if the list supports multiple options at the same time or not void selectByIndex(int index): Selects the option at the given indexvoid selectByValue(java.lang.String value):
Selects all options that match a given valuevoid selectByVisibleText(java.lang.String text):
Selects all options that display text matching a given textThe 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:
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)
{
}
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 (multipleChoiceList.isMultiple() && multipleChoiceList.
getOptions().size() == 4)
{
multipleChoiceList.selectByVisibleText("Reading");
multipleChoiceList.selectByVisibleText("Sports");
multipleChoiceList.selectByVisibleText("Traveling");
}
multipleChoiceList.deSelectByValue("sports");
You can also deselect an option by its index:
multipleChoiceList.deselectByIndex(0);
Or by its visible text:
multipleChoiceList.deselectByVisibleText("Sports");
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 {
}
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.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:
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;
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())
{
}
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 (masters.isEnabled() && masters.isDisplayed())
{
if (!masters.isSelected())
{
masters.click();
}
}
You can select a radio button by clicking on it after it has been selected.
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.");
}
}
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.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.
emailUpdates
".WebElement emailUpdates = driver.findElement(By.
id("emailUpdates"))
;
if (emailUpdates.isEnabled() && emailUpdates.isDisplayed())
{
}
System.out.println
the method, display messages indicating whether the verification was successful or not.if (emailUpdates.isEnabled() && emailUpdates.isDisplayed())
{
if (!emailUpdates.isSelected())
{
emailUpdates.click();
}
}
You can deselect a checkbox by clicking on it after it has been selected.
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.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Selenium Training | Nov 19 to Dec 04 | View Details |
Selenium Training | Nov 23 to Dec 08 | View Details |
Selenium Training | Nov 26 to Dec 11 | View Details |
Selenium Training | Nov 30 to Dec 15 | View Details |
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 .