Checkboxes can be identifies in html DOM with tag as 'input' and type as 'checkbox' as shown in below screenshot.
capture all the checkboxes in a webpage:
e.getAttribute("value") returns the value of a particular checkbox.
e.getAttribute("checked") returns null if a particular checkbox is not checked else return true.
let's see some of the implementations on checkboxes in selenium
List<webelement> checkboxes = driver.findElements(By.cssSelector("input[type='checkbox']"));But let's say, we want to capture a particular group of checkboxes (based on name attribute), in the above screenshot, as u can see, we have a group of checkboxes with all as atribute name 'language'
List<webelement> checkboxes = driver.findElements(By.cssSelector("input[type='checkbox'][name='language']"));Let's see the code for the checkbox operations:
package controls; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class CheckBoxes { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://www.qavalidation.com/p/demo.html"); Listcheckboxes = driver.findElements(By.cssSelector("input[type='checkbox'][name='language']")); //get the 2nd and 3rd checkboxes and check checkboxes.get(1).click(); checkboxes.get(2).click(); for(int i=0;i<checkboxes.size();i++){ WebElement e=checkboxes.get(i); if(e.getAttribute("value").contains("Java") && e.getAttribute("checked")==null) { e.click(); //check, if the checkbox is 'Java' and not checked } } for (WebElement e1 : checkboxes) { System.out.print("CheckBox:"+ e1.getAttribute("value")+"---"); System.out.println("checked:"+ e1.getAttribute("checked"));//checked or not } } }
OutPut:
CheckBoxTestingBasics---checked: null CheckBoxSelenium---checked: true CheckBoxHTML---checked: true CheckBoxJava---checked: true CheckBoxC#---checked: null
e.getAttribute("value") returns the value of a particular checkbox.
e.getAttribute("checked") returns null if a particular checkbox is not checked else return true.
No comments:
Post a Comment