[英]How can I check a checkbox in Selenium WebDriver with Java?
我在 Java 中使用 Selenium 来测试 Web 应用程序中复选框的检查。 这是我的代码:
boolean isChecked = driver.findElement((By.xpath(xpath1))).isSelected();
但是此代码返回不正确的值。 HTML 中的复选框:
<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active">
<span class="ui-chkbox-icon ui-icon ui-icon-check ui-c"></span>
</div>
<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default">
<span class="ui-chkbox-icon ui-icon ui-c ui-icon-blank"></span>
</div>
如何使用 Java 在 Selenium WebDriver 中解决此问题?
您不能使用 isSelected(),因为它不是标准的 HTML 输入元素。
我建议的解决方案是:您可以获取类属性并检查活动属性:
if(driver.findElement((By.xpath(xpath1))).getAttribute('class') == 'ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active')
return True
else
return False
问题主要是因为您创建的复选框不是 HTML 具有的标准输入复选框元素,而是自定义的。 为了检查它,您可以对其执行单击操作,看看它是否有效。
driver.findElement(By.cssSelector('div.ui-chkbox-box)).click(); // Check the checkbox
为了验证它是否被选中,您可以验证元素的类,当它处于活动ui-state-active
将ui-state-active
到 div 元素。
就是这样 -
try{
driver.findElement(By.cssSelector('div.ui-state-active')); // Find the element using the class name to see if it exists
}
catch(NoSuchElementException e){
System.out.println('Element is not checked');
}
或者获取元素的class属性,然后使用它来查看它是否存在。
driver.findElement(By.cssSelector('div.ui-chkbox-box')).getAttribute('class');
我设法解决了它,但这不是一个太漂亮的解决方案:
String a = driver.findElement((By.xpath(xpath1))).getAttribute("class");
System.out.print(a.contains("ui-state-active"));
对于更棘手的情况:
复选框有一个伪 CSS 选择器,“选中”。
因此,您可以像这样将 'checked' 添加到 CSS 选择器中:
let check = !!driver.findElement({css:"div.ui-chkbox-box:checked"});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.