使用Selenium WebDriver和java检查该元素不存在的最佳方法

我尝试下面的代码,但似乎它不起作用…有人能告诉我最好的方法吗?

public void verifyThatCommentDeleted(final String text) throws Exception { new WebDriverWait(driver, 5).until(new ExpectedCondition() { @Override public Boolean apply(WebDriver input) { try { input.findElement(By.xpath(String.format( Locators.CHECK_TEXT_IN_FIRST_STATUS_BOX, text))); return false; } catch (NoSuchElementException e) { return true; } } }); } 

我通常使用几种方法(成对)来validation元素是否存在:

 public boolean isElementPresent(By locatorKey) { try { driver.findElement(locatorKey); return true; } catch (org.openqa.selenium.NoSuchElementException e) { return false; } } public boolean isElementVisible(String cssLocator){ return driver.findElement(By.cssSelector(cssLocator)).isDisplayed(); } 

请注意,有时selenium可以在DOM中找到元素,但它们可能是不可见的,因此selenium将无法与它们进行交互。 因此在这种情况下检查可见性的方法有帮助。

如果你想等待元素,直到它出现,我找到的最佳解决方案是使用流畅的等待:

 public WebElement fluentWait(final By locator){ Wait wait = new FluentWait(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }); return foo; }; 

希望这可以帮助)

而不是使用findElement,执行findElements并检查返回元素的长度为0.这就是我使用WebdriverJS的方式,我希望它在Java中也能正常工作

无法评论“meteor测试手册”,因为我没有代表,但我想提供一个例子,花了我很长时间才弄明白:

 Assert.assertEquals(0, wd.findElements(By.locator("locator")).size()); 

此断言validationDOM中没有匹配的元素并返回零值,因此断言在元素不存在时传递。 如果它存在,它也会失败。

使用findElements而不是findElement

如果找不到匹配的元素而不是exception, findElements将返回一个空列表。 此外,我们可以确保元素存在与否。

例如:List elements = driver.findElements(By.yourlocatorstrategy);

 if(elements.size()>0){ do this.. } else { do that.. } 
 int i=1; while (true) { WebElementdisplay=driver.findElement(By.id("__bar"+i+"-btnGo")); System.out.println(display); if (display.isDisplayed()==true) { System.out.println("inside if statement"+i); driver.findElement(By.id("__bar"+i+"-btnGo")).click(); break; } else { System.out.println("inside else statement"+ i); i=i+1; } } 
 WebElement element = driver.findElement(locator); Assert.assertNull(element); 

如果元素不存在,则上述断言将通过。