'Selenium ignore if element not present

I have the below code for my selenium, where I need to click on carousel icons and get all the images one by one, but sometimes that carousel doesn't have more than one image and thus arrow icon is not present and clickable.

 new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();

How can I handle the exception where the element is not clickable ??



Solution 1:[1]

Two ways to fix it

  1. Use findElements that would return a list of web element if found otherwise size of list will be 0

     try {
         if (driver.findElements(By.cssSelector(".arrow-icon ")).size() > 0 ) {
             System.out.println("Size is > 0 so there must be at least one web element, do some interaction below like click etc");
             new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
         }
         else {
             System.out.println("Size is 0, so web element must not be present, do something here that would make it available");
         }
     }
     catch (Exception e) {
         // TODO: handle exception
     }
    
  2. Use risky code inside directly try

     try {
         new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
     }
     catch (Exception e) {
         // TODO: handle exception
     } 
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cruisepandey