Selenium – 等到元素不可见

在下面的代码中,我尝试等到元素可见:

var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.ElementIsVisible(By.Id("processing"))); 

是否可以告诉驱动程序等到该元素不可见?

是的,可以使用方法invisibilityOfElementLocated

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

以下应该等到元素不再显示,即不可见(或10秒后超时)

 var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10)); wait.Until(driver => !driver.FindElement(By.Id("processing")).Displayed); 

如果使用id processing找不到元素,它将抛出exception。

 var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10)); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("processing"))); 

我们的想法是等到元素不可见。 第一行设置元素必须消失的等待时间; 这是10秒钟。 第二行使用selenium来检查是否满足条件“invisibilityofElementLocated”。 元素通过其id在主题案例中找到,即id="processing" 。 如果元素在请求的时间段内没有消失,则会引发超时exception并且测试将失败。

使用隐形方法,这是一个示例用法。

 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); } } 

是的,您可以创建自己的ExpectedCondition,只是将其显示为不可见

以下是如何在python中执行此操作:

 from selenium.webdriver.support.expected_conditions import _element_if_visible class invisibility_of(object): def __init__(self, element): self.element = element def __call__(self, ignored): return not _element_if_visible(self.element) 

以及如何使用它:

 wait = WebDriverWait(browser, 10) wait.until(invisibility_of(elem)) 

我知道这已经过时了,但既然我正在寻找解决方案,我想我会添加自己的想法。

如果设置IgnoreExceptionTypes属性,上面给出的答案应该有效:

 var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10)); wait.IgnoreExceptionTypes = new[] { typeof(NoSuchElementException) } wait Until(driver => !driver.FindElement(By.Id("processing")).Displayed); 
 public void WaitForElementNotVisible(string id, int seconds) { try { var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(seconds)); wait.Until(driver1 => !visibility(id)); Console.WriteLine("Element is not visible.."); } catch (WebDriverTimeoutException) { Assert.Fail("Element is still visible.."); } } bool visibility(string id) { bool flag; try { flag = driver.FindElement(By.Id(locator)).Displayed; } catch (NoSuchElementException) { flag = false; } return flag; } 

在下面的代码中用于停止驱动程序几秒钟

System.Threading.Thread.Sleep(20000);