在while循环中验证isDisplayed()WebElement属性

我正在尝试编写一个while循环,以针对加载元素检查isDisplayed()属性,如果可见加载窗口,则显示“正在加载”。如果加载窗口消失,则while循环将退出。

private By superPoseLoading = By.xpath("//span[@class='loading']");

while (true) {

    if (driver.findElement(superPoseLoading).isDisplayed() == true) {
        System.out.println("is loading");

    }else {
        break;
    }
}

但是即使if条件为true,程序也不会发送消息,并且循环会中断。

liuyan515 回答:在while循环中验证isDisplayed()WebElement属性

我的方法与其他一些答案略有不同-如果它们都不对您有用,请随时尝试:

By loadingIndicator = By.xpath("//span[@class='loading']");
boolean loadingFinished = false;

while (!loadingFinished) 
{
    System.out.println("is loading");

    // attempt to find the loading indicator,catch exception if it is not found
    try {
        WebElement loader = driver.findElement(loadingIndicator);

        // check isDisplayed(),set found to true
        if (!loader.isDisplayed()) loadingFinished = true;

        // handle exception where loadmask no longer exists
    } catch (NoSuchElementException e) {
        loadingFinished = true;
        e.printStackTrace();
    }
}

此代码正在检查是否存在加载掩码,并处理如果不存在的情况NoSuchElementException。如果loadingFinished为假,或者如果在加载程序上调用true返回loader.isDisplayed(),则将findElement设置为NoSuchElementException,这意味着该元素不存在并且正在加载已经完成。

但是,如果您想简化此代码,则可以使用ExpectedConditions类:

WebDriverWait wait = new WebDriverWait(driver,30);

// first,wait for the loadmask to be visible to avoid race condition
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='loading']")));

// now,wait for load mask to disappear -- loading complete after this
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//span[@class='loading']")));
,

您不需要if语句,也不需要将true分配给.isDisplayed()方法,因为它始终返回布尔值。

 while (driver.findElement(superPoseLoading).isDisplayed()) {
                System.out.println("is loading");
            }
,

例如,当元素不存在时,此方法可能会引发异常问题。我建议使用这样的方法:

By superPoseLoadingLocator = By.xpath("//span[@class='loading']");
List<WebElement> waiter = driver.findElements(superPoseLoadingLocator);
while (!waiter.isEmpty() && waiter.get(0).isDisplayed()){
    System.out.println("Loading...");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
   waiter = driver.findElements(superPoseLoadingLocator);
}
// .. do the staff after the loading has been completed

非常抱歉在这里使用Thread.sleep()。我只是在展示一个主意。

本文链接:https://www.f2er.com/3144128.html

大家都在问