Search code examples
javaseleniumtry-catchnosuchelementexception

findElement method showing an exception


i'm need to click a button which may appear with a 50 percent chance, decided to use try/catch with findElementBy. Nevertheless try/catch doesn't work and I'm getting an exception. Maybe there is a more efficient way to handle that button?

driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
WebDriverWait wait = new WebDriverWait(driver,5);
try {
    WebElement element = driver.findElement(By.xpath("buttonXpath"));
    element.click();
}
catch (NoSuchElementException e){ }

Solution

  • Use method to check if this element is on your screen:

    if (!driver.findElementsByXPath("buttonXpath`enter code here`").isEmpty()) {
       driver.findElementByXPath("buttonXpath`enter code here`").click();
    }