Have you noticed the ubiquity of web forms while surfing the internet? Almost every website or web-application you visit has an interface in the form of web-forms to collect the necessary information about yourself. A webform comprises web elements such as checkbox, radio button, password, drop down to collect user data.
If you are going to perform automated browser testing for your website or web-application then you simply can’t afford to drop-out the forms from your test automation scripts. In the case of test automation, Selenium has an API (Application Programming Interface) that helps to find these web elements and take subsequent actions on them like selecting a value or entering some text.
This article will help you to understand how you can access web forms in Selenium to automate the web application. I will be using the JUnit Framework with some annotations to execute our Selenium automation testing later in this article.
To begin our learning with, we’ll first understand what a WebElement is, how can it be accessed in Selenium Automation, and then go about seeing the basic form elements like the input boxes, buttons, the actions that can be performed on these forms and finally writing a script to handle a form and run it on various browsers. If you are already aware of the basics then feel free to skip through the sections according to yourself:
What Is A WebElement?
In simple words, anything present on a webpage constitutes a WebElement. Examples can be a text box, a radio button, etc. Selenium Webdriver provides an interface that is called the WebElement which is responsible for all the possible actions that take place on the web page. To locate the web elements, the Selenium web driver provides the two methods which are given below- findElement()
- findElements().
findElement(): It locates the single web element. After finding the element is found it is returned as a WebElement object. Let us now see the syntax of findElement(), but before we start using the WebElement object in our test script we need to make note of one very important point.
We need to import the following packages to start creating objects of the WebElements:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebElement;
Syntax for findElement():
WebElement ele = driver.findElement(By.id("id");
WebElement ele = driver.findElement(By.xpath("xpath");
findElements(): It returns a list of WebElements that corresponds to the locator defined in the method.
The syntax for findElements() is as shown below:
List<WebElement> ele = driver.findElements(By.xpath("xpath");
Now that we are thorough with the understanding of the WebElement interface, along with the difference between findElement() & findElements() method in Selenium automation testing. It is time to deep dive into these web elements. We will now list down all the web fields that may be involved in your website or web application form. Now we will learn how to access web forms in Selenium WebDriver.
How To Locate Web Elements
Now we know that what different types of web elements we can come across in our application, We need to identify these web elements through our Selenium automation testing scripts and to do so first we need to find the locators. Locators are the parameters given to the findElement() or findElements() methods which help to retrieve the web element by using its properties like the ID, Name, Class, etc. In general, we have 8 locators in Selenium that are widely used:- ID
- Name
- Tag Name
- Class Name
- LinkText
- Partial LinkText
- XPath
- CSS Selector
WebElement eid = driver.findElement(By.id(“email”);
WebElement pswd = driver.findElement(By.name(“password”);
WebElement sbmtBtn = driver.findElement(By.xpath(“//input[@value=”submit”]”);
Types of Fields
To subsequently build the scripts to access forms in Selenium WebDriver, we need to understand the various fields that we will have to handle in our test automation scripts. Let's see how to access these Web elements using Selenium Web Driver with Java. Selenium represents the form element as an object of Web Element. It has an API to find the elements and take action on them like entering text into text boxes, clicking on the buttons, etc. Now we will explore the methods that Selenium makes available to access the form element. Let us try to dig a little more about these WebElements one by one.
Input Box
The input box is a primary element in any form. No form is complete without user input. It can be of two types:Text Field Box – Text boxes that display the value as is entered by the user.
Password Field Box – Text boxes that display special characters (mostly ‘*’) when the value is entered by the user.
The following image representing the input boxes inside a web form.
Buttons
Buttons are the most important fields to consider while you access forms for Selenium automation testing. There is no point in filling up a form if there is no interface to submit the same. Buttons are simply used to submit whatever information we have filled in our text boxes. This can be submitting some form of data or simply submitting the sign-in information to the server.CheckBox
In most of the websites that are widely used we see a small box that enables us to check or uncheck it. Mostly in agreement sections wherein the user needs to confirm the understanding of these policies. The checkbox is used to return a boolean value, if it is checked then it would return True else would return false.Radio Button
A radio button is shown in the form of a circle on any web page. Mostly it is used to show the "Gender" on sign up forms. That is what a radio button is. It is similar to a checkbox only difference being if we are given multiple radio buttons we can select just one, while in the case of multiple checkboxes, we can opt multiple of them.Link
We all face the common problem of forgetting our account passwords. Noticed the Forgot Password link on the screens? That is what a link is. It redirects us to a new web page or a new window pop-up or a similar thing. It links us to a new URL altogether.Drop Down
There are times for a website where there are multiple options for a specific category. Say a website to book your flight tickets. To pick up the Origin & Destination city we often see a list with multiple values. This list which has an arrow at the rightmost end to expand and show the values is called a drop-down. It provides a list of options to the user thereby giving access to one or multiple values as per the requirement.Below is a snapshot of the Facebook Sign up form.
How To Interact With Web Elements
Now, let's see how we access the forms elements in Selenium and how different actions can be performed on each one of them.Input Box
To handle any input box, we must be able to enter information, clear information, or get information from the box. Selenium offers the following methods to work with text boxes are:- sendKeys()
- clear()
- getText()
driver.findElement(By.id(“username”).sendKeys(“test@gmail.com”);
The above statement would enter the Email ID as abc@gmail.com into a text box whose ID is username. Now, to clear a pre-entered text or the text that you last entered can be wiped clean with the clear() method.
driver.findElement(By.id(“username”)).clear();
The third method that can be used on a text box is the getText() method. It’ll fetch the text that is written in a text box in case we need to validate some existing or entered text.
String nameText = driver.findElement(By.id(“username”)).getText();
The above line of code would return the text, let us take the text entered by the first line of code above, i.e. test@gmail.com and store it in nameText variable of string type. There might be chances when the text is present in the value property. In such a scenario we will use the getAttribute() method in place of getText().
String nameText = driver.findElement(By.id(“username”)).getAttribute(“value”);
Buttons
We can submit the information by using buttons. This can be done through click actions on the same. The following are the two methods that are available in selenium to perform actions on the buttons.- click()
- submit()
driver.findElement(By.id(“submtLogIn”).click();
driver.findElement(By.id(“submtLogIn”).submit();
CheckBox
To interact with checkbox, we’ll use the following Selenium methods:- click()
- isSelected()
driver.findElement(By.id(“name”)).click();
Now that we can check/uncheck a checkbox, we might first need to know the state of a checkbox before performing a certain action with Selenium automation testing. To get the state we use isSelected() method which would return a boolean value. This means if the checkbox is checked we’d get a True else we’ll get False.
boolean state = driver.findElement(By.id(“name”)).isSelected();
Radio Button
The actions performed on the radio button are similar to those on a checkbox and we can use the same methods as above for the radio button as well.- click()
- isSelected()
Link
Links are generally embedded in a web page for us to navigate to a new screen or a popup or a form. We can either do a click action on them or can get the text that it holds and then proceed with our execution.- click()
- getText()
Dropdown
Dropdowns are very commonly and widely used for selecting among a range of options. There is a wide variety of methods that we can use with dropdowns. Let us see them and their corresponding syntax & usage one by one.selectByVisibleText(String)- It selects the value from the dropdown by comparing it with visible text, that is passed as a parameter.
selectByIndex(int)- Selects option based on the index in the drop-down menu with integer parameter passed as the index.
selectByValue(String)- It selects the option in the dropdown, based on the value in string format.
In a similar way we can deselect any selected value from the dropdown using any of the below options:
deselectByVisibleText(String)
deselectByIndex(int)
deselectByValue(String)
deSelectAll()
To select an option from the dropdown in selenium, syntax can be as follows:
Select se=new Select(driver.findElement(By.id("nation")));
se.selectByValue("Ind");
To select the single or multiple options some methods are given below:
getAllSelectedOptions()- It is used to get the list of all selected option in the dropdown.
getFirstSelectedOption()- This method would return the first option that has been selected from the dropdown and unlike the above method it would return a single web element and not a list.
getOptions()- This method would enable us to get a list of all available options in a dropdown.
isMultiple()- To check if a dropdown can take multiple options, we can use isMultiple() method which would return a boolean value.
To get a list of options we can write our piece of code by referencing a list object:
Select se=new Select(driver.findElement(By.id("nation")));
List<WebElement> list=se.getOptions();
Now let's try to perform the basic operations and handling of form elements.
Working Example of Form Elements
Here is a practical demonstration of the test script, how to access forms in Selenium.
Facebook Sign up Scriptpackage com.qa.demo.testcases; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestFaceBookForm { public static WebDriver driver; @BeforeClass public static void setUp() { //Launch FireFox Browser and Hit the URL System.setProperty("webdriver.gecko.driver","/home/khawer/Desktop/geckodriver"); driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("https://facebook.com"); } @Test public void fillForm() { // Enter First Name WebElement fName = driver.findElement(By.xpath("//input[@name='firstname']")); fName.sendKeys("--Enter you name here--"); // Enter Last Name WebElement lName = driver.findElement(By.xpath("//input[@name='lastname']")); lName.sendKeys("--Enter your last name--"); // We are writing the following two lines just to check the clear function lName.clear(); lName.sendKeys("XYZ"); // Enter Email WebElement eMail = driver.findElement(By.xpath("//input[@name='reg_email__']")); eMail.sendKeys("--Enter mail or contact number--"); // Enter Password WebElement pwd = driver.findElement(By.xpath("//input[@name='reg_passwd__']")); pwd.sendKeys("--Enter a valid password here--"); // Select Method for drop downs Select date = new Select(driver.findElement(By.xpath("(id('day'))"))); date.selectByVisibleText("25"); Select month = new Select(driver.findElement(By.xpath("(id('month'))"))); month.selectByVisibleText("Mar"); Select year = new Select(driver.findElement(By.xpath("(id('year'))"))); year.selectByVisibleText("1985"); driver.findElement(By.className("_58mt")).click(); WebElement sgnUp = driver.findElement(By.xpath("//button[@id='u_0_13']")); sgnUp.click(); } @AfterClass public static void tearDown() { //driver.quit(); } }