Handle ElementNotVisibleException in Selenium Webdriver

  • ElementNotVisibleException is one of the most frequently occurred exceptions we face in selenium webdriver while performing automation of web applications.
  • You may get the exception : org.openqa.selenium.ElementNotVisibleException.
  • It indicates that although an element is present in the DOM, but it is not visible on screen,  and so Selenium WebDriver  is not able to be interact  with this particular web element.

Why we face ElementNotVisibleException ?

  • If  you are trying to interact with a particular web element that is present in DOM, but selenium is unable to interact with an element on a web page, then you will get ElementNotVisibleException  exception. Your locator is right but still you are getting an exception. Why ?

There are multiple reasons which may cause this exception:

Case 1 (XPath of WebElements): 

The Xpath you are using for locating a particular web element is correct, but  that is matching with more than one element.

Solutions: 

  • Try to write a Xpath that can uniquely identify your web element. We can also solve this problem using below code snippet. driver.findElements() will give us the list of elements, we are  fetching the first element from the list and clicking on it.
driver.findElements(By.xpath("locator")).get(0).click();
  • You can also use Explicit wait to wait till the web  element becomes clickable. In the below code snippet, selenium web driver will wait for 20 seconds until element becomes clickable.
WebDriverWait w = new WebDriverWait(driver, 20);
WebElement element=w.until(ExpectedConditions.elementToBeClickable(driver.findElement(locator)));
element.click();

Case 2 (Dynamic Loading): 

Selenium Web driver got a feature of performing  auto scroll to a web element and perform desired operations. However, sometimes in case of dynamic loading , you may need to explicitly perform scrolling operations.

Solutions: 

  • You can use Javascript DOM API for that. In below code snippet,  Javascript method scrollIntoView() scrolls the page until the mentioned element becomes fully visible.
WebElement Element = driver.findElement(By.id("xyz"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();",Element );

Case 3 (AJAX Calls): 

AJAX calls (Asynchronous JavaScript) allows parts of a web page to got refresh, without reloading the entire page. If you want to perform some action on a web element which is still loading because of AJAX calls, then you may get NoSuchElementException or ElementNotclickableException (if performing click operation) or ElementNotVisibleException.
Solutions: 

  • You can use explicit wait (code provided in Case 1 solution) for solving this problem.
Scroll to Top