提问人:Heap Yazılım 提问时间:12/24/2019 更新时间:12/24/2019 访问量:301
如果 selenium 中不存在元素,如何编写代码 [JAVA]
How to write code if not an element exists in selenium [JAVA]
问:
这是一个登录测试方案。有两个用户。他们是有效和无效的用户。弹出的确定单击正在测试中工作。
<---- 问题 ----->
如果---->(如果不存在元素)---- print(“成功登录”),
else ---->(如果元素存在)-----弹出窗口确定单击。以其他用户身份登录。
我不能这样做,没有这样的元素情况。
错误
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.
}
答:
0赞
KunduK
12/24/2019
#1
使用 () 返回元素列表,然后检查列表的大小,如果存在超过 0 表示按钮并单击它。findElements
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");
}
0赞
Wasim Daas
12/24/2019
#2
尝试使用 driver.findElements 而不是 driver.findElement
在这种情况下,如果元素不存在 temp.getSize() == 0
0赞
Aravind
12/24/2019
#3
您可以使用 try catch 块而不是 if/else 块,类似于 以下代码
尝试
{
driver.findElement(By.xpath("html/body/div/div/div[3]/button[1]"));
}
捕获 (NoSuchElementException)
{
Console.WriteLine("Element does not exist!");
}
您还可以找到是否存在这样的元素。
布尔值 isPresent = driver.findElements(By.yourLocator).size() > 0
评论