Selenium Webdriver: Best Practices for Handling NoSuchElementException

After much searching and reading, I still don't understand how best to handle a failed statement with Webdriver. I would think that this is a common and basic functionality. All I want to do is:

  • find item
  • if there is, tell me
  • if not, tell me

I want to present the results to a non-technical audience, so if you throw away “NoSuchElementExceptions” with a full stack trace, this will not help. I just want a nice message.

My test:

@Test
public void isMyElementPresent(){
  //  WebElement myElement driver.findElement(By.cssSelector("#myElement"));
    if(driver.findElement(By.cssSelector("#myElement"))!=null){
        System.out.println("My element was found on the page");
    }else{
            System.out.println("My Element was not found on the page");
        }
    }

I still get a NoSuchElementException when I force a failure. Do I need to try and catch? Can I include Junit and / or Hamcrest statements to create a more meaningful message without the need for System.out.println?

+4
3

. Javadoc API findElement findElements, , findElement . findElements .

, WebElement , findElements.

.

List<WebElement> elems = driver.findElements(By.cssSelector("#myElement"));
if (elems.size == 0) {
        System.out.println("My element was not found on the page");
} else
        System.out.println("My element was found on the page");
}
+8

- , ,

  public boolean isElementExists(By by) {
    boolean isExists = true;
    try {
        driver.findElement(by);
    } catch (NoSuchElementException e) {
        isExists = false;
    }
    return isExists;
}
+2

How to use xPath inside a try-catch, passing the element attribute, attribute and text as follows:

try {
    driver.FindElement(
        By.XPath(string.Format("//{0}[contains(@{1}, '{2}')]", 
        strElemType, strAttribute, strText)));
    return true;
}
catch (Exception) {
    return false;
}
0
source

Source: https://habr.com/ru/post/1534386/


All Articles