How to check if an element is visible with WebDriver

后端 未结 11 1568
臣服心动
臣服心动 2020-12-04 13:14

With WebDriver from Selenium 2.0a2 I am having trouble checking if an element is visible.

WebDriver.findElement returns a WebElement<

11条回答
  •  旧时难觅i
    2020-12-04 13:56

    I have the following 2 suggested ways:

    1. You can use isDisplayed() as below:

      driver.findElement(By.id("idOfElement")).isDisplayed();
      
    2. You can define a method as shown below and call it:

      public boolean isElementPresent(By by) {
        try {
          driver.findElement(by);
          return true;
        }
      catch (org.openqa.selenium.NoSuchElementException e) {
          return false;
        }
      }
      

    Now, you can do assertion as below to check either the element is present or not:

    assertTrue(isElementPresent(By.id("idOfElement")));
    

提交回复
热议问题