Java 硒:等待元素消失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24535720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:47:12  来源:igfitidea点击:

Selenium: Waiting for an element do disappear

javaseleniumwaitinvisible

提问by Christoph Zabinski

I posed with a difficult task. I am fairly new to selenium and still working through the functionalities of waiting for elements and alike.

我提出了一项艰巨的任务。我对硒相当陌生,并且仍在研究等待元素等功能。

I have to manipulate some data on a website and then proceed to another. Problem: the manipulation invokes a script that makes a little "Saving..." label appear while the manipulated data is being processed in the background. I have to wait until I can proceed to the next website.

我必须在一个网站上处理一些数据,然后再处理另一个。问题:操作调用了一个脚本,当在后台处理操作的数据时,该脚本会出现一个小“正在保存...”标签。我必须等到我可以继续访问下一个网站。

So here it is: How do i wait for and element to DISAPPEAR? Thing is: It is always present in the DOM but only made visible by some script (I suppose, see image below). The palish code contains the said element

所以这里是:我如何等待元素消失?事情是:它始终存在于 DOM 中,但只能通过某些脚本可见(我想,请参见下图)。 淡色代码包含所述元素

This is what I tried but it just doesn't work - there is no waiting, selenium just proceeds to the next step (and gets stuck with an alert asking me if I want to leave or stay on the page because of the "saving...").

这是我尝试过的,但它不起作用 - 没有等待,硒只是继续下一步(并且由于“保存”而被困在一个警报中,询问我是否要离开或留在页面上。 ..”)。

private By savingLableLocator = By.id("lblOrderHeaderSaving");

    public boolean waitForSavingDone(By webelementLocator, Integer seconds){
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    Boolean element = wait.until(ExpectedConditions.invisibilityOfElementLocated(webelementLocator));
    return element;
}

UPDATE / SOLUTION:

更新/解决方案:

I came up ith the following solution: I built my own method. Basically it checks in a loop for the CssValue to change.

我想出了以下解决方案:我建立了自己的方法。基本上它会在循环中检查 CssValue 的变化。

the loops checks for a certain amount of time for the CSSVALUE "display" to go from "block" to another state.

循环检查 CSSVALUE“显示”从“阻塞”到另一个状态的特定时间。

public void waitForSavingOrderHeaderDone(Integer _seconds){
    WebElement savingLbl = driver.findElement(By.id("lblOrderHeaderSaving"));   
    for (int second = 0;; second++) {
        if (second >= _seconds)
            System.out.println("Waiting for changes to be saved...");
        try {
            if (!("block".equals(savingLbl.getCssValue("display"))))
                break;
        } catch (Exception e) {

        }
    }

回答by Pierre-luc S.

I'm not sure, but you can try something like this :)

我不确定,但你可以尝试这样的事情:)

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //time in second
WebElement we = driver.findElement(By.id("lblOrderHeaderSaving"));   
assertEquals("none", we.getCssValue("display"));

回答by Nguyen Vu Hoang

Webdriver has built in waiting functionality you just need to build in the condition to wait for.

Webdriver 内置了等待功能,您只需要在等待条件中构建即可。

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
   .withTimeout(30, SECONDS)
   .pollingEvery(5, SECONDS)
   .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
 public WebElement apply(WebDriver driver) {
   return (driver.findElements(By.id("lblOrderHeaderSaving")).size() == 0);
 }
});

回答by 1-14x0r

This works with selenium 2.4.0. you have to use the invisibility mehtod to find it.

这适用于硒 2.4.0。您必须使用隐形方法才能找到它。

final public static boolean waitForElToBeRemove(WebDriver driver, final By by) {
    try {
        driver.manage().timeouts()
                .implicitlyWait(0, TimeUnit.SECONDS);

        WebDriverWait wait = new WebDriverWait(UITestBase.driver,
                DEFAULT_TIMEOUT);

        boolean present = wait
                .ignoring(StaleElementReferenceException.class)
                .ignoring(NoSuchElementException.class)
                .until(ExpectedConditions.invisibilityOfElementLocated(by));

        return present;
    } catch (Exception e) {
        return false;
    } finally {
        driver.manage().timeouts()
                .implicitlyWait(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    }
}

回答by TheFreddyKilo

You can wait for a WebElement to throw a StaleElementReferenceException like this:

您可以等待 WebElement 像这样抛出 StaleElementReferenceException:

public void waitForInvisibility(WebElement webElement, int maxSeconds) {
    Long startTime = System.currentTimeMillis();
    try {
        while (System.currentTimeMillis() - startTime < maxSeconds * 1000 && webElement.isDisplayed()) {}
    } catch (StaleElementReferenceException e) {
        return;
    }
}

So you would pass in the WebElement you want to wait for, and the max amount of seconds you want to wait.

因此,您将传入要等待的 WebElement 以及要等待的最大秒数。

回答by Abhinav Saxena

I used following C# code to handle this, you may convert it to Java

我使用以下 C# 代码来处理这个问题,您可以将其转换为 Java

    public bool WaitForElementDisapper(By element)
    {
        try
        {
            while (true)
            {
                try
                {
                    if (driver.FindElement(element).Displayed)
                        Thread.Sleep(2000);
                }
                catch (NoSuchElementException)
                {
                    break;
                }
            }
            return true;
        }
        catch (Exception e)
        {
            logger.Error(e.Message);
            return false;
        }
    }

回答by Santosh Pillai

You can also try waiting for the ajax calls to complete. I've used this to check when the page load is complete and all the elements are visible.

您也可以尝试等待 ajax 调用完成。我用它来检查页面加载何时完成并且所有元素都可见。

Here's the code - https://stackoverflow.com/a/46640938/4418897

这是代码 - https://stackoverflow.com/a/46640938/4418897

回答by Hendrik

You could use XPath and WebDriverWait to check whether display: noneis present in the style attribute of an element. Here is an example:

您可以使用 XPath 和 WebDriverWait 来检查display: none元素的 style 属性中是否存在。下面是一个例子:

// Specify the time in seconds the driver should wait while searching for an element which is not present yet.
int WAITING_TIME = 10;

// Use the driver for the browser you want to use.
ChromeDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, WAITING_TIME);

// Replace ELEMENT_ID with the ID of the element which should disappear. 
// Waits unit style="display: none;" is present in the element, which means the element is not visible anymore.
driver.wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='ELEMENT_ID'][contains(@style, 'display: block')]")));