Multiple Checkboxes – through selenium web
driver API
Working with checkboxes
in website with different examples to select and unselect the checkboxes using
selenium webdriver API Select class,
Below in this tutorial we get to know about, working with multiple checkbox.
In the real time
scenario,There are many cases were we need to select multiple checkboxes or un-select
the multiple checkbox. Below is the generic code to work with multiple checkbox.
Bello We will be passing two parameters, where one is the wait
time to wait for an element to be clickable and then perform the check
operation. Only when the Checkbox control is not selected.
import org.openqa.selenium.By;
import
org.openqa.selenium.NoSuchElementException;
import
org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import
org.openqa.selenium.support.ui.ExpectedConditions;
import
org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
public class CheckBoxExample {
private WebDriver driver;
@Test
private void testMultipleCheckBoxExample()
throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("App URL");
WebElement element1 =
driver.findElement(By.cssSelector("input[value=itunes]"));
WebElement
element2 = driver.findElement(By.cssSelector("input[value=lastfm]"));
WebElement
element3 = driver.findElement(By.cssSelector("input[value=spotify]"));
WebElement[] elements = { element1, element2,
element3 };
safeSelectCheckBoxesExample (10, elements);
}
public void safeSelectCheckBoxesExample(int
waitTime, WebElement... elements) throws Exception {
WebElement checkElement = null;
try {
if (elements.length > 0) {
for (WebElement currentElement : elements) {
checkElement
= currentElement;
WebDriverWait
wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.elementToBeClickable(currentElement));
WebElement checkBox = currentElement;
if (checkBox.isSelected())
System.out.println("CheckBox " +
currentElement+ " is already selected");
else
checkBox.click();
}
} else {
System.out.println("Expected at least
one element as an argument to safeSelectCheckboxesExample function");
}
} catch (StaleElementReferenceException e) {
System.out.println("Element - " +
checkElement + " is not attached
to the page document like DOM "
+ e.getStackTrace());
} catch (NoSuchElementException e) {
System.out.println("Element =" +
checkElement + " was not found in DOM"+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to select
checkbox in givin web site" + e.getStackTrace());
}
}
}
No comments:
Post a Comment