首页 > 解决方案 > 如何在查找 UI 上不存在的 web 元素时绕过隐式等待条件?

问题描述

我正在自动化一个场景,其中特定的 Web 元素可能会或可能不会显示在 UI 上。如果它正在显示,那么我想对其执行特定操作。我使用下面的逻辑相同

try{
if(element.isDisplayed())
    {
     //perform action on the element if it is visible
    }
}
catch(Exception e)
    {
    }

只要元素在 UI 上可见,代码就可以正常工作。但是在不显示元素的情况下,'element.isDisplayed()' 会等待元素 10 秒(即我为驱动程序会话定义的隐式等待时间)。

我希望我的脚本不要等待元素出现的那 10 秒,而是继续执行进一步的操作。知道我应该在这里采用什么方法吗?

标签: seleniumui-automationimplicitwait

解决方案


看起来你可以通过减少超时值来实现WebDriverWait

尝试创建一个布尔函数来检查元素是否存在特定时间。

public boolean checkElement(By locator, int seconds) {
    boolean find = false;
    try {
        new WebDriverWait(driver, seconds).until(ExpectedConditions.presenceOfElementLocated(locator));
        find = true;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return find;
}

只需致电:

By locator = By.name("yourLocator");

if(checkElement(locator, 1)) {
    //perform here
    ....
}

以下进口:

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

请删除implicitWait您之前声明的内容。


推荐阅读