环境:使用 Java 的 Selenium Webdriver
1)运行搜索
2)搜索后将显示 5 个项目,并带有 5 个复选框
3)我想获取复选框的数量
4)复选框的类名称为“复选框”
请建议
谢谢 !!
最快和最简单的方法是通过您提供的类名查找复选框元素的列表。
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()
}
以下将显示页面上存在的所有复选框
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
}
}