简体   繁体   中英

How to find the total number of checkboxes present on web page using Selenium Webdriver - Java?

1) run a Search
2) after search 5 items will be displayed with 5 check-boxes against them
3) I want to get the number of check-boxes
4) check-boxes have class name "checkbox"

Please suggest

Thanks !!

Quickest and simplest method is to find a list of the checkbox elements by the className you've provided.

List<WebElement> boxes = driver.findElements(By.className("checkbox"));
int numberOfBoxes = boxes.length();

If you want the number of checkboxes per search result, you'd need to loop for each result.

List<WebElement> results = driver.findElements(By.xpath("//relevant_xpath_from_your_html"));
for (Webelement result : results){
     List<WebElement> boxes = result.findElements(By.className("checkbox"));
     int numberOfBoxes = boxes.length()
}

The following will show all checkboxes present on a page

System.out.println(
    driver.findElements(By.cssSelector("input[type='checkbox']")).size()
); 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;

public class Checkbox {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "E:\\java\\WebDriver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://rahulshettyacademy.com/AutomationPractice/");
        driver.findElement(By.cssSelector("input[id='checkBoxOption1']")).click();//select checkbox 1
        Assert.assertTrue(driver.findElement(By.cssSelector("input[id='checkBoxOption1']")).isSelected());//validated checkbox selection
        
        //Thread.sleep(4000);//delay process to see the check and uncheck activity

        driver.findElement(By.cssSelector("input[id='checkBoxOption1']")).click();//deselect checkbox 1
        Assert.assertFalse(driver.findElement(By.cssSelector("input[id='checkBoxOption1']")).isSelected());//validated checkbox deselection
        
        //to get checkbox counts on the page.
        System.out.println("The checkbox count is "+ driver.findElements(By.cssSelector("input[type='checkbox']")).size());//select checkbox 1

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM