如何等待Selenium中的元素不再存在

我正在测试用户单击删除按钮的UI,表条目消失。 因此,我希望能够检查表条目不再存在。

我已经尝试使用ExpectedConditions.not()来反转ExpectedConditions.presenceOfElementLocated() ,希望它意味着“期望不存在指定的元素”。 我的代码是这样的:

 browser.navigate().to("http://stackoverflow.com"); new WebDriverWait(browser, 1).until( ExpectedConditions.not( ExpectedConditions.presenceOfElementLocated(By.id("foo")))); 

但是,我发现即使这样做,我得到一个由NoSuchElementException引起的TimeoutExpcetion ,说元素“foo”不存在。 当然,没有这样的元素是我想要的,但我不想抛出exception。

那么我怎么能等到一个元素不再存在呢? 我更喜欢一个不依赖于捕获exception的示例(如我所知),exception应该抛出exception行为。

你也可以用 –

 new WebDriverWait(driver, 10).until(ExpectedConditions.invisibilityOfElementLocated(locator)); 

如果您查看它的源代码,您可以看到处理NoSuchElementExceptionstaleElementReferenceException

 /** * An expectation for checking that an element is either invisible or not * present on the DOM. * * @param locator used to find the element */ public static ExpectedCondition invisibilityOfElementLocated( final By locator) { return new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { try { return !(findElement(locator, driver).isDisplayed()); } catch (NoSuchElementException e) { // Returns true because the element is not present in DOM. The // try block checks if the element is present but is invisible. return true; } catch (StaleElementReferenceException e) { // Returns true because stale element reference implies that element // is no longer visible. return true; } } 

解决方案仍然依赖于exception处理。 这是非常好的,即使标准的预期条件依赖于findElement()抛出的exception。

我们的想法是创建一个自定义的预期条件

  public static ExpectedCondition absenceOfElementLocated( final By locator) { return new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { try { driver.findElement(locator); return false; } catch (NoSuchElementException e) { return true; } catch (StaleElementReferenceException e) { return true; } } @Override public String toString() { return "element to not being present: " + locator; } }; } 

你为什么不简单地找到elements的大小。 我们知道如果元素不存在,元素大小的集合将为0

 if(driver.findElements(By.id("foo").size() > 0 ){ //It should fail }else{ //pass } 
 // pseudo code public Fun ElemtDisappear(locator) { webelement element=null; iList elemt =null; return driver=> { try { elemt = driver.findelements(By.locator); if(elemt.count!=0) { element=driver.findelement(By.locator); } } catch(Exception e) { } return(elemnt==0)?element:null; }; // call function public void waitforelemDiappear(driver,locator) { webdriverwaiter wait = new webdriverwaiter(driver,time); try { wait.until(ElemtDisappear(locator)); } catch(Exception e) { } } 

因为findelement在元素不可靠性上抛出exception。所以我使用findelements实现。 请随意更正并根据您的需要使用它。

我找到了一种解决方法,以高效的方式为我解决这个问题,使用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; } }