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

前端 未结 8 1078
误落风尘
误落风尘 2020-12-05 05:29

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.

    WebEle         


        
相关标签:
8条回答
  • 2020-12-05 05:35

    You can retrieve a list of elements by using driver.findElements("Your elements") and then search for the element. if the list doesn't contains the element you got yourself your desired behavior :)

    0 讨论(0)
  • 2020-12-05 05:42

    Best solution

      protected boolean isElementPresent(WebElement el){
            try{
                el.isDisplayed();
                return true;
            }
            catch(NoSuchElementException e){
                return false;
            }
        }
    
    0 讨论(0)
  • 2020-12-05 05:43

    If you are testing using junit and that is the only thing you are testing you could make the test expect an exception using

    @Test (expected=NoSuchElementException.class)
    public void someTest() {
        driver.findElement(By.className("commentEdit"));
    }
    

    Or you could use the findElements method that returns an list of elements or an empty list if none are found (does not throw NoSuchElementException):

    ...
    List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit"));
    assertTrue(deleteLinks.isEmpty());
    ...
    

    or

    ....
    assertTrue(driver.findElements(By.className("commentEdit")).isEmpty());
    ....
    
    0 讨论(0)
  • 2020-12-05 05:43

    Use assertFalse :)

    assertFalse(isElementPresent(By.className("commentEdit")));
    
    0 讨论(0)
  • 2020-12-05 05:48

    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

    0 讨论(0)
  • 2020-12-05 05:48
    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;
     }
    }
    
    0 讨论(0)
提交回复
热议问题