How to Select Checkbox in Selenium Webdriver Java
Selenium is an
open-source
web-based automation tool that is
implemented using a web driver. We will be using geckodriver
because Selenium 3 enables
geckodriver as the default WebDriver implementation for Firefox.
Pre-requisites:
- geckodriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
it's a 4 steps process:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver and browse to the website.
-
Get all checkbox
flex
elements as Web elements usingwebdriver.findElements()
function and CSS selector. - Iterate over all these elements and get the desired checkbox and then hit click.
Let’s see all the above steps in the code. We will use
Webelment.click()
function to select a checkbox.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; import java.util.Random; public class SelectCheckbox { public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\SelectCheckbox\\src\\main\\resources\\geckodriver.exe"; public static Random random = new Random(); public static void main(String[] args) { //set firefox webdriver System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH); WebDriver driver = new FirefoxDriver(); //get the firefox browser & Browse the Website String siteLink = "https://docs.google.com/forms/d/e/1FAIpQLSd3hbwlnuLuwVVnP3iEAjQwXQuZ7PuiTNMuuYe0TcHHYqZ6uQ/viewform"; driver.get(siteLink); //Get all checkbox elements List<WebElement> allElements = driver.findElements(By.cssSelector("div.ulDsOb")); //remove extra divs allElements.remove(0); allElements.remove(0); //Select a random check box int randomNumber = random.nextInt(0,2); //Hit Click allElements.get(randomNumber).click(); System.out.println("Checkbox No."+ (randomNumber+1) +" shall be clicked."); //Select a random check box randomNumber = random.nextInt(3,allElements.size()-1); //Hit Click allElements.get(randomNumber).click(); System.out.println("Checkbox No."+ (randomNumber+1) +" shall be clicked."); } }
Output:
All resources used in this tutorial are attached:
- source code
- geckdriver.exe
Comments
Post a Comment