【问题标题】:How to find the total number of checkboxes present on web page using Selenium Webdriver - Java?如何使用 Selenium Webdriver - Java 查找网页上存在的复选框总数?
【发布时间】:2013-07-01 09:14:19
【问题描述】:

环境:使用 Java 的 Selenium Webdriver

1) 运行搜索
2) 搜索后将显示 5 个项目,并带有 5 个复选框
3) 我想获取复选框的数量
4) 复选框的类名为“checkbox”

请推荐

谢谢!!

【问题讨论】:

  • 请粘贴一些您要测试的页面的html代码?

标签: java selenium webdriver


【解决方案1】:

最快最简单的方法是根据您提供的类名查找复选框元素的列表。

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

如果您想要每个搜索结果的复选框数量,您需要为每个结果循环。

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()
}
【解决方案2】:

以下将显示页面上存在的所有复选框

System.out.println(
    driver.findElements(By.cssSelector("input[type='checkbox']")).size()
); 

【讨论】:

    【解决方案3】:
    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
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      相关资源
      最近更新 更多