这是一个登录测试场景。 有两个用户。他们是有效用户和无效用户。弹出确定点击正在测试中。
<---- 问题 ----->
If ---->(如果不存在元素)---- print("登录成功"),
else ----> (if an element exists) ----- 弹出ok点击。使用其他用户登录。
没有这样的元素情况我不能这样做。
错误
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div/div/div[3]/button[1]"}
(Session info: chrome=79.0.3945.88)
代码
WebElement temp444 = driver.findElement(By.xpath("html/body/div/div/div[3]/button[1]"));
System.out.println(temp444.getSize());
if(temp.getSize()!=null){
temp.click(); // ----> It's working!
}
else {
System.out.println("good working"); // ----> It isn't working.
}
最佳答案
使用 findElements
() 返回元素列表,然后检查列表的大小,如果大于 0 表示按钮存在并单击它。
List<WebElement> elements = driver.findElements(By.xpath("html/body/div/div/div[3]/button[1]"));
System.out.println(elements.size());
if(elements.size()>0)
{
elements.get(0).click();
}
else {
System.out.println("good working");
}
关于java - 如果 Selenium 中不存在元素,如何编写代码[JAVA],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59467273/