How to use ElementNotVisibleException class of org.openqa.selenium package

Best Selenium code snippet using org.openqa.selenium.ElementNotVisibleException

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

ElementNotVisibleException org.openqa.selenium.ElementNotVisibleException;

ElementNotVisibleException raised when element exists in DOM of page but not visible on page.

Like, HTML Elements of type ="hidden", here the element will be present in DOM though not visible on page. Visibility required hight and width property of and element should >0

Example

The below code snippet is an example of performing action on hidden element which is present in DOM though not visible on page so the action will throw ElementNotVisibleException

copy
1driver.findElement(By.id("hiddenelementid")).sendKeys("xyz";

Solutions

  • Check for duplicate xpath
  • Try to access the element with different locator
  • Use explicit wait till element become visible

Code Snippets

Here are code snippets that can help you understand more how developers are using

copy
1package com.tls.liferaylms.test;
2
3import java.util.List;
4
5import org.junit.After;
6import org.junit.Before;
7import org.openqa.selenium.Alert;
8import org.openqa.selenium.By;
9import org.openqa.selenium.ElementNotVisibleException;
10import org.openqa.selenium.NoAlertPresentException;
11import org.openqa.selenium.NoSuchElementException;
12import org.openqa.selenium.TimeoutException;
13import org.openqa.selenium.WebDriver;
14import org.openqa.selenium.WebElement;
15
16import com.gargoylesoftware.htmlunit.ElementNotFoundException;
17import com.liferay.portal.kernel.log.Log;
18import com.liferay.portal.kernel.log.LogFactoryUtil;
19import com.tls.liferaylms.test.util.Context;
20import com.tls.liferaylms.test.util.Sleep;
21
22public class SeleniumTestCase {
23	protected WebDriver driver;
24	protected String baseUrl;
25	private Log log = null;
26	private boolean acceptNextAlert = true;
27
28	@Before
29	public void setUp() throws Exception {
30		driver = SeleniumDriverUtil.getDriver();
31		baseUrl = Context.getBaseUrl();	
32	}
33
34	@After
35	public void tearDown() throws Exception {
36
37	}
38
39	private boolean isElementPresent(By by) {
40		try {
41			driver.findElement(by);
42			return true;
43		} catch (NoSuchElementException e) {
44			return false;
45		} catch (ElementNotVisibleException e) {
46			return false;
47		} catch (ElementNotFoundException e) {
48			return false;
49		} catch (Exception e) {
50			return false;
51		}
52	}
53	
54	public WebElement getElement(By by){
55		try {
56//			Sleep.waitFor(by, driver);
57			return driver.findElement(by);
58		} catch(TimeoutException e){
59			return driver.findElement(by);
60		} catch (NoSuchElementException e) {
61			return null;
62		} catch (ElementNotVisibleException e) {
63			return null;
64		} catch (ElementNotFoundException e) {
65			return null;
66		} catch (Exception e) {
67			return null;
68		}
69	}
70	public WebElement getElement(WebElement we,By by){
71		try {
72//			Sleep.waitFor(by, driver);
73			return we.findElement(by);
74		} catch(TimeoutException e){
75			return we.findElement(by);
76		} catch (NoSuchElementException e) {
77			return null;
78		} catch (ElementNotVisibleException e) {
79			return null;
80		} catch (ElementNotFoundException e) {
81			return null;
82		} catch (Exception e) {
83			return null;
84		}
85	}
86	
87	public List<WebElement> getElements(WebElement we,By by){
88		try {
89			return we.findElements(by);
90		} catch (NoSuchElementException e) {
91			return null;
92		} catch (ElementNotVisibleException e) {
93			return null;
94		} catch (ElementNotFoundException e) {
95			return null;
96		} catch (Exception e) {
97			return null;
98		}
99	}
100
101	public List<WebElement> getElements(By by){
102		try {
103			return driver.findElements(by);
104		} catch (NoSuchElementException e) {
105			return null;
106		} catch (ElementNotVisibleException e) {
107			return null;
108		} catch (ElementNotFoundException e) {
109			return null;
110		} catch (Exception e) {
111			return null;
112		}
113	}
114
115	public boolean isAlertPresent() {
116		try {
117			driver.switchTo().alert();
118			return true;
119		} catch (NoAlertPresentException e) {
120			return false;
121		}
122	}
123
124	public String closeAlertAndGetItsText() {
125		try {
126			Alert alert = driver.switchTo().alert();
127			String alertText = alert.getText();
128			if (acceptNextAlert) {
129				alert.accept();
130			} else {
131				alert.dismiss();
132			}
133			return alertText;
134		} finally {
135			acceptNextAlert = true;
136		}
137	}
138	
139	public Log getLog(){
140		if(log==null){
141			log = LogFactoryUtil.getLog(this.getClass());
142		}
143		return log;
144	}
145	
146	/** Get the current line number.
147	 * @return String - Current line number.
148	 */
149	public String getLineNumber() {
150	    return ". At line ".concat(String.valueOf(Thread.currentThread().getStackTrace()[2].getLineNumber()));
151	}
152}
153
Full Screen
copy
1package ToolsQA.MavenDemo;
2
3import java.util.concurrent.TimeUnit;
4
5import org.openqa.selenium.By;
6import org.openqa.selenium.ElementNotVisibleException;
7import org.openqa.selenium.NoSuchElementException;
8import org.openqa.selenium.StaleElementReferenceException;
9import org.openqa.selenium.TimeoutException;
10import org.openqa.selenium.WebDriver;
11import org.openqa.selenium.WebElement;
12import org.openqa.selenium.chrome.ChromeDriver;
13import org.openqa.selenium.support.ui.ExpectedConditions;
14import org.openqa.selenium.support.ui.WebDriverWait;
15
16public class Exceptn {
17
18	static By search = By.cssSelector("input[name='h']");
19
20	public static void main(String A[]) {
21		System.setProperty("webdriver.chrome.driver",
22				"C://Users//srishti.goel//Downloads//chromedriver_win32//chromedriver.exe");
23		WebDriver driver = new ChromeDriver();
24
25		driver.get("https://www.google.com");
26		// WebElement search = driver.findElement(By.id("q"));
27		waitForElement(driver, search);
28
29		driver.findElement(search).sendKeys("hello world");
30
31	}
32
33	public static void waitForElement(WebDriver driver, By w) {
34
35		try {
36			driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
37			WebDriverWait wait = new WebDriverWait(driver, 2);
38		//	wait.until(ExpectedConditions.visibilityOfElementLocated(w));
39			//wait.until(ExceptedConditions.)
40		}
41		catch (TimeoutException e) {
42			System.out.println("Timeout exception");
43		} 
44		catch (NoSuchElementException e) {
45			System.out.println("No such element exception");
46		} catch (ElementNotVisibleException e) {
47
48		} catch (StaleElementReferenceException e) {
49
50		}
51	}
52
53}
54
Full Screen
copy
1package github.isanjeevkumar.selenium;
2
3import java.time.Duration;
4import java.util.NoSuchElementException;
5
6import com.google.common.base.Function;
7
8import org.apache.commons.lang.NotImplementedException;
9import org.openqa.selenium.By;
10import org.openqa.selenium.ElementNotVisibleException;
11import org.openqa.selenium.SearchContext;
12import org.openqa.selenium.WebDriver;
13import org.openqa.selenium.WebElement;
14import org.openqa.selenium.support.ByIdOrName;
15import org.openqa.selenium.support.locators.RelativeLocator;
16import org.openqa.selenium.support.locators.RelativeLocator.RelativeBy;
17import org.openqa.selenium.support.pagefactory.ByChained;
18import org.openqa.selenium.support.ui.WebDriverWait;
19
20import github.isanjeevkumar.enums.RelativeByLocator;
21
22public class WebElementFinder {
23
24    public static WebElement getElement(WebDriver driver, final By elementLocator, int timeOutInSecs)
25            throws Exception {
26        try {
27            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
28            wait.ignoring(NoSuchElementException.class);
29            wait.ignoring(ElementNotVisibleException.class);
30            return wait.until(new Function<WebDriver, WebElement>() {
31                public WebElement apply(WebDriver driver) {
32                    return getElement(driver, elementLocator);
33                }
34            });
35
36        } catch (Exception ex) {
37            System.err.println("Error:" + ex.getMessage());
38            throw ex;
39        }
40
41    }
42
43    public static WebElement getElementByIdOrName(WebDriver driver, final String byIdOrName, int timeOutInSecs)
44            throws Exception {
45        try {
46            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
47            wait.ignoring(NoSuchElementException.class);
48            wait.ignoring(ElementNotVisibleException.class);
49            return wait.until(new Function<WebDriver, WebElement>() {
50                public WebElement apply(WebDriver driver) {
51                    return getByIdOrName(driver, byIdOrName);
52                }
53            });
54
55        } catch (Exception ex) {
56            System.err.println("Error:" + ex.getMessage());
57            throw ex;
58        }
59
60    }
61
62    public static WebElement getElementByChained(WebDriver driver, final ByChained chainedValue, int timeOutInSecs)
63            throws Exception {
64        try {
65            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
66            wait.ignoring(NoSuchElementException.class);
67            wait.ignoring(ElementNotVisibleException.class);
68            return wait.until(new Function<WebDriver, WebElement>() {
69                public WebElement apply(WebDriver driver) {
70                    return getByChained(driver, chainedValue);
71                }
72            });
73
74        } catch (Exception ex) {
75            System.err.println("Error:" + ex.getMessage());
76            throw ex;
77        }
78
79    }
80
81    public static WebElement getElementByRelativeLocator(WebDriver driver, WebElement referenceElement,
82            final By elementLocator, RelativeByLocator relativeBy,
83            int timeOutInSecs)
84            throws Exception {
85        try {
86
87            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
88            wait.ignoring(NoSuchElementException.class);
89            wait.ignoring(ElementNotVisibleException.class);
90            return wait.until(new Function<WebDriver, WebElement>() {
91                public WebElement apply(WebDriver driver) {
92                    return getRelativeElement(driver, referenceElement, elementLocator, relativeBy);
93                }
94            });
95
96        } catch (Exception ex) {
97            System.err.println("Error:" + ex.getMessage());
98            throw ex;
99        }
100
101    }
102
103    private static WebElement getElement(final SearchContext searchContext, final By elementLocator) {
104        WebElement element = searchContext.findElement(elementLocator);
105        if (element.isDisplayed() && element.isEnabled()) {
106            return element;
107        }
108        throw new ElementNotVisibleException("WebElement with locator " + elementLocator + " is not visible.");
109    }
110
111    private static WebElement getByIdOrName(final SearchContext searchContext, final String elementLocatorValue) {
112        WebElement element = searchContext.findElement(new ByIdOrName(elementLocatorValue));
113        if (element.isDisplayed() && element.isEnabled()) {
114            return element;
115        }
116        throw new ElementNotVisibleException("WebElement with locator " + elementLocatorValue + " is not visible.");
117    }
118
119    private static WebElement getByChained(final SearchContext searchContext, final ByChained getByChained) {
120        WebElement element = searchContext.findElement(getByChained);
121        if (element.isDisplayed() && element.isEnabled()) {
122            return element;
123        }
124        throw new ElementNotVisibleException("WebElement with locator " + getByChained.toString() + " is not visible.");
125    }
126
127    private static WebElement getRelativeElement(final SearchContext searchContext, WebElement referenceElement,
128            final By elementLocator, RelativeByLocator relativeLocator) {
129        RelativeBy relativeBy = RelativeLocator.with(elementLocator);
130        WebElement element = null;
131        switch (relativeLocator) {
132            case ABOVE:
133                element = searchContext.findElement(relativeBy.above(referenceElement));
134                break;
135            case BELOW:
136                element = searchContext.findElement(relativeBy.below(referenceElement));
137                break;
138            case LEFT_OF:
139                element = searchContext.findElement(relativeBy.toLeftOf(referenceElement));
140                break;
141            case NEAR:
142                element = searchContext.findElement(relativeBy.near(referenceElement));
143                break;
144            case RIGHT_OF:
145                element = searchContext.findElement(relativeBy.toRightOf(referenceElement));
146                break;
147            default:
148                throw new NotImplementedException("relativeLocatorBy is not implemented. Please check.");
149
150        }
151
152        if (element.isDisplayed() && element.isEnabled()) {
153            return element;
154        }
155        throw new ElementNotVisibleException(
156                "WebElement with locator " + elementLocator.toString() + " is not visible.");
157    }
158}
159
Full Screen
copy
1public boolean isPrebuiltTestButtonVisible() {
2    try {
3
4        if (preBuiltTestButton.isEnabled()) {
5
6            return true;
7
8        } else {
9
10            return false;
11        }
12
13    } catch (Exception e) {
14
15        e.printStackTrace();
16        return false;
17    }
18}
19
Full Screen
copy
1    try{
2        if( driver.findElement(By.xpath("//div***")).isDisplayed()){
3          System.out.println("Element is Visible");
4        }
5}
6catch(NoSuchElementException e){
7   else{
8     System.out.println("Element is InVisible");
9        }
10}
11
Full Screen
copy
1public boolean isElementExist(By by) {
2    int count = driver.findElements(by).size();
3    if (count>=1) {
4        Logger.LogMessage("isElementExist: " + by + " | Count: " + count, Priority.Medium);
5        return true;
6    }
7    else {
8        Logger.LogMessage("isElementExist: " + by + " | Could not find element", Priority.High);
9        return false;
10    }   
11}
12
13public boolean isElementNotExist(By by) {
14    int count = driver.findElements(by).size();
15    if (count==0) {
16        Logger.LogMessage("ElementDoesNotExist: " + by, Priority.Medium);
17        return true;
18    }
19    else {
20        Logger.LogMessage("ElementDoesExist: " + by, Priority.High);
21        return false;
22    }   
23}
24
25public boolean isElementVisible(By by) {
26    try {
27        if (driver.findElement(by).isDisplayed()) {
28            Logger.LogMessage("Element is Displayed: " + by, Priority.Medium);
29            return true;
30        }
31    }
32    catch(Exception e) {       
33        Logger.LogMessage("Element is Not Displayed: " + by, Priority.High);
34        return false;
35    }       
36
37    return false;
38}
39
Full Screen
copy
1public boolean isElementFound( String text) {
2        try{
3            WebElement webElement = appiumDriver.findElement(By.xpath(text));
4            System.out.println("isElementFound : true :"+text + "true");
5        }catch(NoSuchElementException e){
6            System.out.println("isElementFound : false :"+text);
7            return false;
8        }
9        return true;
10    }
11
12    text is the xpath which you would be passing when calling the function.
13the return value will be true if the element is present else false if element is not pressent
14
Full Screen
copy
1public static boolean isElementVisible(WebElement webElement, int timeOut) {
2    try {
3      WebDriverWait wait = new WebDriverWait(driver, timeOut);
4      wait.until(ExpectedConditions.visibilityOf(webElement));
5      return true;
6    } catch (org.openqa.selenium.NoSuchElementException e) {
7      return false;
8    }
9  }
10
Full Screen
copy
1public static boolean isElementVisible(final By by)
2    throws InterruptedException {
3        boolean value = false;
4
5        if (driver.findElements(by).size() > 0) {
6            value = true;
7        }
8        return value;
9    }
10
Full Screen
copy
1if (!driver.FindElement(By.Name("newtagfield")).Displayed)      //if the tag options is not displayed
2    driver.FindElement(By.Id("expand-folder-tags")).Click();    //make sure the folder and tags options are visible
3
Full Screen
copy
1assertTrue(isElementPresent(By.id("idOfElement")));
2
Full Screen
copy
1@Test
2// visibilityOfElementLocated has been statically imported
3public demo(){
4    By searchButtonSelector = By.className("search_button");
5    WebDriverWait wait = new WebDriverWait(driver, 10);
6    driver.get(homeUrl);
7
8    WebElement searchButton = wait.until(                
9            visibilityOfElementLocated
10            (searchButtonSelector)); 
11
12    //clicks the search button 
13    searchButton.click();
14
Full Screen
copy
1export default function isDisplayedInViewport () {
2    return getBrowserObject(this).execute(isDisplayedInViewportScript, {
3        [ELEMENT_KEY]: this.elementId, // w3c compatible
4        ELEMENT: this.elementId // jsonwp compatible
5    })
6}
7
Full Screen
copy
1/**
2 * check if element is visible and within the viewport
3 * @param  {HTMLElement} elem  element to check
4 * @return {Boolean}           true if element is within viewport
5 */
6export default function isDisplayedInViewport (elem) {
7    const dde = document.documentElement
8
9    let isWithinViewport = true
10    while (elem.parentNode && elem.parentNode.getBoundingClientRect) {
11        const elemDimension = elem.getBoundingClientRect()
12        const elemComputedStyle = window.getComputedStyle(elem)
13        const viewportDimension = {
14            width: dde.clientWidth,
15            height: dde.clientHeight
16        }
17
18        isWithinViewport = isWithinViewport &&
19                           (elemComputedStyle.display !== 'none' &&
20                            elemComputedStyle.visibility === 'visible' &&
21                            parseFloat(elemComputedStyle.opacity, 10) > 0 &&
22                            elemDimension.bottom > 0 &&
23                            elemDimension.right > 0 &&
24                            elemDimension.top < viewportDimension.height &&
25                            elemDimension.left < viewportDimension.width)
26
27        elem = elem.parentNode
28    }
29
30    return isWithinViewport
31}
32
Full Screen
copy
1/** 
2 * Demo of a java version of webdriverio's isDisplayedInViewport
3 * https://github.com/webdriverio/webdriverio/blob/v5.0.0-beta.2/packages/webdriverio/src/commands/element/isDisplayedInViewport.js
4 * The super class GuiTest just deals with setup of the driver and such
5 */
6class VisibleDemoTest extends GuiTest {
7    public static String readScript(String name) {
8        try {
9            File f = new File("selenium-scripts/" + name + ".js");
10            BufferedReader reader = new BufferedReader( new FileReader( file ) );
11            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
12        } catch(IOError e){
13            throw new RuntimeError("No such Selenium script: " + f.getAbsolutePath()); 
14        }
15    }
16
17    public static Boolean isVisibleInViewport(RemoteElement e){
18        // according to the Webdriver spec a string that identifies an element
19        // should be deserialized into the corresponding web element,
20        // meaning the 'isDisplayedInViewport' function should receive the element, 
21        // not just the string we passed to it originally - how this is done is not our concern
22        //
23        // This is probably when ELEMENT and ELEMENT_KEY refers to in the wd.io implementation
24        //
25        // Ref https://w3c.github.io/webdriver/#dfn-json-deserialize
26        return js.executeScript(readScript("isDisplayedInViewport"), e.getId());
27    }
28
29    public static Boolean isVisibleInViewport(String xPath){
30        driver().findElementByXPath("//button[@id='should_be_visible']");
31    }
32
33    @Test
34    public demo_isVisibleInViewport(){
35        // you can build all kinds of abstractions on top of the base method
36        // to make it more Selenium-ish using retries with timeouts, etc
37        assertTrue(isVisibleInViewport("//button[@id='should_be_visible']"));
38        assertFalse(isVisibleInViewport("//button[@id='should_be_hidden']"));
39    }
40}
41
Full Screen
copy
1wait=WebDriverWait(driver,timeout=10,poll_frequency=1)
2element=wait.until(element_has_text((By.CSS_SELECTOR,"div#finish>h4"),"Hello World!"))
3
4class element_has_text(object):
5"""An expectation for checking that an element has a particular text.
6
7locator - used to find the element
8returns the WebElement once it has the particular text
9"""
10def __init__(self,locator,expected_text):
11    self.locator=locator
12    self.expected_text=expected_text
13
14def __call__(self,driver):
15    element = driver.find_element(*self.locator)
16    if (element.text==self.expected_text):
17        return element
18    else:
19        return False
20
Full Screen
copy
1element = None
2i = 6
3while element is None:
4    try:
5        wait = WebDriverWait(driver, 5, poll_frequency=1)
6        element = wait.until(expected_conditions.visibility_of_element_located(el))
7    except:
8        driver.refresh()
9        i = i - 1
10        print(i)
11        if i < 0:
12            raise Exception('Element not found')
13
Full Screen
copy
1from selenium import webdriver
2from selenium.webdriver.common.by import By
3from selenium.webdriver.support.ui import WebDriverWait
4from selenium.webdriver.support import expected_conditions as EC
5from selenium.common.exceptions import *
6
7driver = webdriver.Firefox()
8# Load some webpage
9wait = WebDriverWait(driver, 10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])
10element = wait.until(EC.element_to_be_clickable((By.XPATH, "//div")))
11
Full Screen
copy
1wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("your locator value")));
2
Full Screen
copy
1wait.until(ExpectedConditions.ElementIsVisible(By.xpath("your locator value")));
2
Full Screen
copy
1driver.Manage().Window.Size = new System.Drawing.Size(1928, 1060);
2
Full Screen
copy
1public static void Listget (WebDriver driver) throws Exception 
2
3{
4    Thread.sleep(5000);
5    UtilityMethod.getAppLocaters(driver, "closeicon").click();
6
7    Actions action = new Actions(driver);
8    WebElement we = driver.findElement(By.xpath("//li[@class='parent dropdown  aligned-left']"));
9    Thread.sleep(5000);
10    action.moveToElement(we).build().perform();
11
12    List<WebElement>links = driver.findElements(By.xpath("//span[@class='menu-title']"));
13    int total_count = links.size();       
14    System.out.println("Total size :=" +total_count);           
15     for(int i=0;i<total_count;i++)
16        {             
17            WebElement  element = links.get(i);
18            String text = element.getAttribute("innerHTML");
19            System.out.println("linksnameis:="  +text);
20
21            try{
22                    File src = new File("D:ReadFile.xlsx");
23                    FileInputStream fis = new FileInputStream(src);
24                    XSSFWorkbook wb=new XSSFWorkbook(fis);
25                    XSSFSheet sh = wb.getSheetAt(0);
26
27                    sh.createRow(i).createCell(1).setCellValue(text);
28
29                    FileOutputStream fos = new FileOutputStream(new File("D:/ReadFile.xlsx"));
30                    wb.write(fos);
31                    fos.close();
32                }
33                catch(Exception e)
34                {
35                    System.out.println(e.getMessage());
36                }
37
38
39        }
40    }
41}
42
Full Screen
copy
1int var_ele_size= driver.findElements(By.xpath("locator")).size();
2
Full Screen
copy
1driver.findElements(By.xpath("locator")).get(var_ele_size-1).click();
2
Full Screen
copy
1By.cssSelector("div.signIn div#_loginButton")
2
Full Screen
copy
1By.cssSelector("form#_loginForm div#_loginButton")
2
Full Screen
copy
1By.xpath("//div[@class='page']//div[@id='_loginButton']")
2
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in ElementNotVisibleException

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)