Webdriver:ExpectedConditions.invisibilityOf无效。总是抛出异常

时间:2017-11-17 08:47:26

标签: java selenium-webdriver

我正在使用ExpectedConditions.invisibilityOf来检查其中一个元素的不可见性,但每次它都会抛出超时异常:

wait.until(ExpectedConditions.invisibilityOf(elementTobeInvisible));

错误讯息:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for invisibility of Proxy element for: DefaultElementLocator 'By.xpath: //button[text()='button text']' (tried for 30 second(s) with 500 MILLISECONDS interval)

我使用element.isDisplayed()检查了相同元素的可见性,它正确返回'false'。

最近我从2.53.0升级了selenium

Webdriver:3.7.1或3.6.0 Chrome:62.0.3202.94(官方版)(64位) 操作系统:Windows 7

2 个答案:

答案 0 :(得分:1)

调查了这个问题,看起来错误的实施:

对于版本2.53.0和3.7.0,隐身方法存在实现差异。

2.53 实施:

public static ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) {
    return new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver webDriver) {
            Iterator var2 = elements.iterator();

            while(var2.hasNext()) {
                WebElement element = (WebElement)var2.next();

                try {
                    if (element.isDisplayed()) {
                        return false;
                    }
                } catch (Exception var5) {
                    ;
                }
            }

            return true;
        }

        public String toString() {
            return "invisibility of all elements " + elements;
        }
    };
}

观察:看看&#34;捕捉(例外 var5)&#34;。在这里,我们将一切都视为例外

3.7.1 实施

public static ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) {
    return new ExpectedCondition() {
        public Boolean apply(WebDriver webDriver) {
            return Boolean.valueOf(elements.stream().allMatch((x$0) -> {
                return ExpectedConditions.isInvisible(x$0);
            }));
        }

        public String toString() {
            return "invisibility of all elements " + elements;
        }
    };
}


private static boolean isInvisible(WebElement element) {
    try {
        return !element.isDisplayed();
    } catch (StaleElementReferenceException var2) {
        return true;
    }
}

观察:我们只捕获 StaleElementReferenceException ,因此在使用该方法时会抛出 TimeoutException ,这是未捕获的

答案 1 :(得分:0)

您可以尝试使用以下代码行代替 -

wait.until(ExpectedConditions.invisibilityOfElementLocated(elementTobeInvisible));

或者你可以简单地调用这样的方法 -

//Wait until Invisibility of element is completed
public void waitForInvisibility(By byElement){
try{
WebDriverWait wait = new WebDriverWait(driver, 120);
wait.until(ExpectedConditions.invisibilityOfElementLocated(byElement));
//May apply thread sleep for 1 or 2 seconds
}catch(Exception e){}}

在调用此方法之前,请声明param By元素,如下所示 -

By byElement = By.cssSelector("Use the element's css selector here");

//或

By byElement = By.xpath("Use the element's XPath here");