How do I verify that an element does not exist in Selenium 2

Viewed 74015

In Selenium 2 I want to ensure that an element on the page that the driver has loaded does not exist. I'm including my naive implementation here.

    WebElement deleteLink = null;
    try {
        deleteLink = driver.findElement(By.className("commentEdit"));
    } catch (NoSuchElementException e) {

    }
    assertTrue(deleteLink != null);

Is there a more elegant way that basically verifies to assert that NoSuchElementException was thrown?

9 Answers

If you're using the Javascript API, you can use WebElement.findElements(). This method will return a Promise with an array of found elements. You can check the length of the array to ensure no items were found.

driver.findElements(By.css('.selector')).then(function(elements) {
  expect(elements.length).to.equal(0)
})

I'm using Chai assertion library inside the Promise's callback to expect a certain value.

Reference: https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html

Best solution

  protected boolean isElementPresent(WebElement el){
        try{
            el.isDisplayed();
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }
public boolean exist(WebElement el){
   try {
      el.isDisplayed();
      return true;
   }catch (NoSuchElementException e){
      return false;
   }
}

if(exist(By.id("Locator details"))==false)

or

WebElement el= driver.findElementby(By.locator("locator details")
public boolean exists(WebElement el)
 try{
  if (el!=null){
   if (el.isDisplayed()){
     return true;

    }
   }
 }catch (NoSuchElementException e){
   return false;
 }
}

Using webdriver find_element_xxx() will raise exception in my code and take us the waiting time of implicit/explicit webdriver wait.

I will go for DOM element check

webdriver.execute_script("return document.querySelector('your css class')")

p.s.

Also found similar discussion on our QA-main sister site here


For full check for visibility+existence

    # check NOT visible the :aftermeet and :viewintro
    #                   !                .      .                       !       !offsetWidth to check visible in pure js ref. https://stackoverflow.com/a/20281623/248616
    css='yourcss'; e=wd.execute_script(f"return document.querySelector('{css}').offsetWidth > 0") ; assert not e

    # check NOT exists :viewintro
    css='yourcss'; e=wd.execute_script(f"return document.querySelector('{css}')") ; assert not e
Related