Selenium WebDriver: Random Error determining if element is visible - selenium

I'm using Selenium 2.2.
I am trying to click on elements which are not displayed at first, but become visible
during the test. At first sometimes the webdriver seemed to work too fast so the Elements were not visible in time resulting in ElementNotVisibleExceptions. I added WebDriverWait to wait for these elements to become visible/clickable. But now I'm getting this random error when using
WebDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id")));
same for
WebDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("id")));
here is the stacktrace
org.openqa.selenium.WebDriverException: Error determining if element is displayed (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 219 milliseconds
Build info: version: '2.20.0', revision: '16008', time: '2012-02-27 19:03:59'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1 build 2600 Service Pack 3', java.version: '1.6.0'
Driver info: driver.version: RemoteWebDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:44)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:516)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:170)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:123)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:438)
at org.openqa.selenium.remote.RemoteWebElement.isDisplayed(RemoteWebElement.java:280)
at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:136)
at org.openqa.selenium.support.ui.ExpectedConditions.access$1(ExpectedConditions.java:135)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:106)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:1)
at org.openqa.selenium.support.ui.ExpectedConditions$11.apply(ExpectedConditions.java:252)
at org.openqa.selenium.support.ui.ExpectedConditions$11.apply(ExpectedConditions.java:1)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:201)
at MyTest.myTest(MyTest.java:xx)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:600)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
This only happens sometimes. Ignoring the WebDriverException might solve this problem, but that doesn't seem like a clean solution. It can't be a timeout issue because i tried setting my timeout limit to a minute and more and it still fails after a couple of milliseconds.
Anybody got a clean solution to that?
Thanks in advance
Edit: btw. I'm using the InternetExplorerDriver

Make sure page has only one modalPanel. Try get visible panel (java):
public WebElement getVisibleModalPanel(){
for (WebElement element : driver.findElements(By.cssSelector('csslocator'))) {
if (element.isDisplayed()) {
return element;
}
}
return null;
}
Implement wait for such thing:
(new WebDriverWait(getDriver(), timeout, 400)).ignoring(StaleElementReferenceException.class).until(
new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
for (WebElement element : driver.findElements(By.cssSelector(locator))) {
if (element.isDisplayed()) {
return true;
}
}
return false;
}
});

Related

org.openqa.selenium.TimeoutException: Supplied function might have stalled error using titleContains() with Selenium 4.0.0-alpha-5 and Java 11

Googling yielded nothing but source code on this timeout and I seem to have no visibility via logs looking at selenium source code. I am wondering if anyone else has run into this issue with selenium
The condition we waited on was the following
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
wait.until(ExpectedConditions.titleContains("Find a doctor"));
org.openqa.selenium.TimeoutException: Supplied function might have stalled
Build info: version: '4.0.0-alpha-5', revision: 'b3a0d621cc'
System info: host: 'localhost', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0', java.version: '11.0.6'
Driver info: driver.version: unknown
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:221)
at com.orderlyhealth.scraper.json.CaredashHelper.getSearchResultsFromProviderImpl(CaredashHelper.java:320)
at com.orderlyhealth.scraper.json.CaredashHelper.getSearchResultsFromProvider(CaredashHelper.java:294)
at com.orderlyhealth.scraper.json.CaredashHelper.runImpl(CaredashHelper.java:65)
at com.orderlyhealth.scraper.json.CaredashHelper.run(CaredashHelper.java:57)
at com.orderlyhealth.scraper.json.JsonController.runBatchImpl(JsonController.java:200)
at com.orderlyhealth.scraper.json.JsonController.executeBatch(JsonController.java:134)
at com.orderlyhealth.scraper.json.JsonController.preRunBatchImpl(JsonController.java:110)
at com.orderlyhealth.scraper.json.JsonController.runBatch(JsonController.java:86)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.webpieces.router.impl.services.ControllerInvoker.invokeController(ControllerInvoker.java:30)
at org.webpieces.router.impl.services.SvcProxyForContent.invokeAndCoerce(SvcProxyForContent.java:56)
at org.webpieces.router.impl.services.SvcProxyForContent.lambda$invokeMethod$1(SvcProxyForContent.java:49)
at java.base/java.util.concurrent.CompletableFuture.uniComposeStage(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.thenCompose(Unknown Source)
at org.webpieces.router.impl.services.SvcProxyForContent.invokeMethod(SvcProxyForContent.java:49)
at org.webpieces.router.impl.services.SvcProxyForContent.lambda$invoke$0(SvcProxyForContent.java:33)
at org.webpieces.util.futures.FutureHelper.syncToAsyncException(FutureHelper.java:169)
at org.webpieces.router.impl.services.SvcProxyForContent.invoke(SvcProxyForContent.java:33)
at org.webpieces.router.impl.services.SvcProxyForContent.invoke(SvcProxyForContent.java:19)
at com.orderlyhealth.serverutil.filters.InternalSvcValidationFilter.filter(InternalSvcValidationFilter.java:33)
at com.orderlyhealth.serverutil.filters.InternalSvcValidationFilter.filter(InternalSvcValidationFilter.java:13)
at org.webpieces.router.impl.loader.ChainFilters$ServiceFilterProxy.invoke(ChainFilters.java:29)
at org.webpieces.router.impl.loader.ChainFilters$ServiceFilterProxy.invoke(ChainFilters.java:17)
at org.webpieces.plugin.json.JacksonCatchAllFilter.filter(JacksonCatchAllFilter.java:44)
at org.webpieces.plugin.json.JacksonCatchAllFilter.filter(JacksonCatchAllFilter.java:28)
at org.webpieces.router.impl.loader.ChainFilters$ServiceFilterProxy.invoke(ChainFilters.java:29)
at org.webpieces.router.impl.loader.ChainFilters$ServiceFilterProxy.invoke(ChainFilters.java:17)
at com.orderlyhealth.serverutil.filters.JobAndBatchIdFilter.filter(JobAndBatchIdFilter.java:33)
at com.orderlyhealth.serverutil.filters.JobAndBatchIdFilter.filter(JobAndBatchIdFilter.java:13)
at org.webpieces.router.impl.loader.ChainFilters$ServiceFilterProxy.invoke(ChainFilters.java:29)
at org.webpieces.router.impl.loader.ChainFilters$ServiceFilterProxy.invoke(ChainFilters.java:17)
at org.webpieces.router.impl.routers.Endpoint.invoke(Endpoint.java:27)
at org.webpieces.router.impl.routeinvoker.ServiceInvoker.invokeService(ServiceInvoker.java:83)
at org.webpieces.router.impl.routeinvoker.ServiceInvoker.lambda$invokeSvc$0(ServiceInvoker.java:67)
at org.webpieces.util.futures.FutureHelper.syncToAsyncException(FutureHelper.java:169)
at org.webpieces.util.futures.FutureHelper.catchBlock(FutureHelper.java:104)
at org.webpieces.util.futures.FutureHelper.catchBlockWrap(FutureHelper.java:142)
at org.webpieces.router.impl.routeinvoker.ServiceInvoker.invokeSvc(ServiceInvoker.java:66)
at org.webpieces.router.impl.routebldr.RequestResponseStream.lambda$openStream$1(RequestResponseStream.java:57)
at org.webpieces.router.impl.routeinvoker.RequestStreamWriter2.handleCompleteRequestImpl(RequestStreamWriter2.java:86)
at org.webpieces.router.impl.routeinvoker.RequestStreamWriter2.processPiece(RequestStreamWriter2.java:68)
at org.webpieces.router.impl.routers.NonStreamingWebAppErrorProxy.lambda$processPiece$0(NonStreamingWebAppErrorProxy.java:41)
at org.webpieces.util.futures.FutureHelper.syncToAsyncException(FutureHelper.java:169)
at org.webpieces.util.futures.FutureHelper.catchBlock(FutureHelper.java:104)
at org.webpieces.router.impl.routers.NonStreamingWebAppErrorProxy.processPiece(NonStreamingWebAppErrorProxy.java:40)
at org.webpieces.router.impl.TxStreamWriter.processPiece(TxStreamWriter.java:24)
at org.webpieces.frontend2.impl.ProxyHttpStream$ProxyWriter.processPiece(ProxyHttpStream.java:161)
at org.webpieces.frontend2.impl.Layer2Http11Handler.lambda$processPiece$7(Layer2Http11Handler.java:210)
at java.base/java.util.concurrent.CompletableFuture.uniComposeStage(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.thenCompose(Unknown Source)
at org.webpieces.frontend2.impl.Layer2Http11Handler.processPiece(Layer2Http11Handler.java:210)
at org.webpieces.frontend2.impl.Layer2Http11Handler.lambda$null$4(Layer2Http11Handler.java:199)
at org.webpieces.util.futures.FutureHelper.syncToAsyncException(FutureHelper.java:169)
at org.webpieces.util.futures.FutureHelper.finallyBlock(FutureHelper.java:55)
at org.webpieces.frontend2.impl.Layer2Http11Handler.lambda$processData$6(Layer2Http11Handler.java:198)
at org.webpieces.util.locking.PermitQueue.processItemFromQueue(PermitQueue.java:82)
at org.webpieces.util.locking.PermitQueue.runRequest(PermitQueue.java:62)
at org.webpieces.frontend2.impl.Layer2Http11Handler.processData(Layer2Http11Handler.java:184)
at org.webpieces.frontend2.impl.Layer2Http11Handler.processCorrectly(Layer2Http11Handler.java:173)
at org.webpieces.frontend2.impl.Layer2Http11Handler.lambda$processWithBackpressure$3(Layer2Http11Handler.java:149)
at java.base/java.util.concurrent.CompletableFuture.uniComposeStage(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.thenCompose(Unknown Source)
at org.webpieces.frontend2.impl.Layer2Http11Handler.processWithBackpressure(Layer2Http11Handler.java:149)
at org.webpieces.frontend2.impl.Layer2Http11Handler.initialDataImpl(Layer2Http11Handler.java:72)
at org.webpieces.frontend2.impl.Layer2Http11Handler.initialData(Layer2Http11Handler.java:48)
at org.webpieces.frontend2.impl.Layer1ServerListener.lambda$initialData$1(Layer1ServerListener.java:62)
at org.webpieces.util.futures.FutureHelper.syncToAsyncException(FutureHelper.java:169)
at org.webpieces.util.futures.FutureHelper.catchBlock(FutureHelper.java:104)
at org.webpieces.util.futures.FutureHelper.catchBlockWrap(FutureHelper.java:142)
at org.webpieces.frontend2.impl.Layer1ServerListener.initialData(Layer1ServerListener.java:61)
at org.webpieces.frontend2.impl.Layer1ServerListener.incomingData(Layer1ServerListener.java:51)
at org.webpieces.asyncserver.impl.ProxyDataListener.incomingData(ProxyDataListener.java:26)
at org.webpieces.nio.impl.threading.ThreadDataListener$DataListeneRunanble.run(ThreadDataListener.java:54)
at org.webpieces.util.threading.SessionExecutorImpl$RunnableWithKey.run(SessionExecutorImpl.java:121)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.util.concurrent.TimeoutException: null
at java.base/java.util.concurrent.CompletableFuture.timedGet(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.get(Unknown Source)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:209)
... 80 common frames omitted
Any ideas how to fix this? It is happens quite a bit to us.
Turns out when you have a bad proxy in the middle, I noticed the browsers would WAIT on the page. This then would cause selenium drivers to hang. It was a very intermittent issue so hard to narrow down to a proxy issue.
This error message...
org.openqa.selenium.TimeoutException: Supplied function might have stalled
Build info: version: '4.0.0-alpha-5', revision: 'b3a0d621cc'
System info: host: 'localhost', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0', java.version: '11.0.6'
Driver info: driver.version: unknown
...implies that TimeoutException occurred while waiting for title to contain the string Find a doctor.
Analysis
I don't see any major change in the defination of the ExpectedConditions titleContains() which is defined as follows:
/**
* An expectation for checking that the title contains a case-sensitive substring
*
* #param title the fragment of title expected
* #return true when the title matches, false otherwise
*/
public static ExpectedCondition<Boolean> titleContains(final String title) {
return new ExpectedCondition<Boolean>() {
private String currentTitle = "";
#Override
public Boolean apply(WebDriver driver) {
currentTitle = driver.getTitle();
return currentTitle != null && currentTitle.contains(title);
}
#Override
public String toString() {
return String.format("title to contain \"%s\". Current title: \"%s\"", title, currentTitle);
}
};
}
However the TimeoutException seems to be arising from ExecutionException which looks a bit odd.
/**
* Repeatedly applies this instance's input value to the given function until one of the following
* occurs:
* <ol>
* <li>the function returns neither null nor false</li>
* <li>the function throws an unignored exception</li>
* <li>the timeout expires</li>
* <li>the current thread is interrupted</li>
* </ol>
*
* #param isTrue the parameter to pass to the {#link ExpectedCondition}
* #param <V> The function's expected return type.
* #return The function's return value if the function returned something different
* from null or false before the timeout expired.
* #throws TimeoutException If the timeout expires.
*/
#Override
public <V> V until(Function<? super T, V> isTrue) {
try {
return CompletableFuture.supplyAsync(checkConditionInLoop(isTrue))
.get(deriveSafeTimeout(), TimeUnit.MILLISECONDS);
} catch (ExecutionException cause) {
if (cause.getCause() instanceof RuntimeException) {
throw (RuntimeException) cause.getCause();
} else if (cause.getCause() instanceof Error) {
throw (Error) cause.getCause();
}
throw new RuntimeException(cause);
} catch (InterruptedException cause) {
Thread.currentThread().interrupt();
throw new RuntimeException(cause);
} catch (java.util.concurrent.TimeoutException cause) {
throw new TimeoutException("Supplied function might have stalled", cause);
}
}
But driver.version: unknown gives us a hint that there is a incompatibility between the version of the binaries you are using.
Additionally, in the next release of Selenium, the constructor of WebDriverWait of selenium3 would be deprecated.
#Deprecated
public WebDriverWait(WebDriver driver, long timeoutInSeconds) {
this(driver, Duration.ofSeconds(timeoutInSeconds));
}
The new constructor of WebDriverWait to be used in selenium4 (currently in Alpha) is:
public WebDriverWait(WebDriver driver, Duration timeout) {
this(
driver,
timeout,
Duration.ofMillis(DEFAULT_SLEEP_TIMEOUT),
Clock.systemDefaultZone(),
Sleeper.SYSTEM_SLEEPER);
}
The usage should be:
new WebDriverWait(driver, Duration.ofSeconds(10));
Java 11
As you are using java.version: '11.0.6', Selenium is still not compatible with Java 11. But once Java 11 ships and Buck supports it the toolchain witll be rejiged to support Java 11.
Solution
The strategic solution will be to install the latest version of JDK 8u251 and execute the #Tests
Reference
You can find a relevant detailed discussion in Unable to import org.openqa.selenium.WebDriver using Selenium and Java 11
it is saying clearly i.e TimeoutException, change the timeout ,you given 30 ms but actually need more than that...give it as more than 30 , it will work smoothly.

MicrosoftWebDriver loading web driver null

I have the error when run selenium on local machine which is Windows 10 Enterpise 64-bit (Microsoft Edge Version: 25.10586.672.0)and Microsoft WebDriver - Release 10240. My Selenium version is: 3.6.0
public class SeleniumTest {
private WebDriver driver;
#BeforeClass
public void getWebDriver() {
try {
System.setProperty("webdriver.edge.driver", "myapp/driver/MicrosoftWebDriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.edge();
capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
capabilities.setCapability(CapabilityType.PAGE_LOAD_STRATEGY, "eager");
capabilities.setPlatform(Platform.WIN10);
capabilities.setBrowserName(BrowserType.EDGE);
capabilities.setVersion("");
driver = new EdgeDriver(capabilities);
} catch (Exception e) {
e.printStackTrace();
}
driver.get(Constant.URL);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
}
#AfterClass
public void quitDriver() throws InterruptedException {
Thread.sleep(3000);
driver.quit();
}
#Test ()
public void aTest() {
}
#Test ()
public void bTest() {
}
}
When I run code it open the Edge Browser and has error:
org.openqa.selenium.NoSuchSessionException: null (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 873 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'computername', ip: 'myip', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_111'
Driver info: driver.version: EdgeDriver
You may consider to look into the Release Notes as it mentions:
Updating .NET bindings to not send incorrect W3C Firefox capabilities
Previously, RemoteWebDriver would send the same capabilities dictionary
using both the "desiredCapabilities" and "capabilities" properties when
requesting a new remote session. In the case of the language bindings
expressly requesting to use the legacy Firefox driver, the capabilities
dictionary will include properties that are invalid for the W3C-compliant
remote server. To resolve that issue, we will mask the explicit attempt by
setting a property that causes the .NET RemoteWebDriver to send a
legacy-only compatible new session request when explicitly requesting the
legacy driver.
I don't see any significant error as such in your code except one, to see NoSuchSessionException. Instead of:
DesiredCapabilities capabilities = DesiredCapabilities.edge();
You should use:
DesiredCapabilities cap = new DesiredCapabilities();
It's possible you also need to start a driver service, i.e.
service = new EdgeDriverService.Builder()
.usingDriverExecutable(new File("path/to/my/MicrosoftWebDriver.exe"))
.usingAnyFreePort()
.build();
service.start();
Have a look at this example of an EdgeDriver.

Difficult to run the script in selenium webdriver which contains HtmlUnitDriver

I am unable to run the basic selenium script which contains the HtmlUnitDriver. If I try to run the code I get the following error.
Code:
public class SampleUnitDriver
{
public static void main(String[] args) throws Exception
{
HtmlUnitDriver unitDriver = new HtmlUnitDriver();
unitDriver.get("http://google.com");
System.out.println("Title of the page is -> " + unitDriver.getTitle());
Thread.sleep(3000L);
WebElement searchBox = unitDriver.findElement(By.className("gsfi"));
searchBox.sendKeys("Selenium");
WebElement button = unitDriver.findElement(By.name("gbqfba"));
button.click();
System.out.println("Title of the page is -> " + unitDriver.getTitle());
}
}
Error:
Title of the page is -> Google
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Returned node was not a DOM element
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'user-PC', ip: '192.168.1.52', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: driver.version: SampleUnitDriver
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByCssSelector(HtmlUnitDriver.java:1060)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByClassName(HtmlUnitDriver.java:1032)
at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1725)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1721)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:1367)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1721)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:606)
at com.digitalmqc.automation.action.SampleUnitDriver.main(SampleUnitDriver.java:16)
The class name gsfi of the input box is generated by javascript so you have 2 options:
Easy One: Just select it by using the id lst-ib
Better One: Wait for the element to be fully interactive. The reason behind this one being better is that you are trying to input text into the box which javascript plays a role. The former option may throw some unexpected errors.

Webdriver is not detecting when a web element becomes invisible

I am having trouble getting this "invisibilityOfElementLocated()" method to work. Here is the
code I am using and I am witnessing the element disappear after about 35 seconds with my own eyes but Webdriver does not detect this and crashes on this code and skips the test. Would love if someone had a diffferent method that worked better.
if ( driver.findElement( By.xpath( "//div[#class='Caption']" )).isDisplayed() ) {
System.out.println("Caption is visible.");
}
WebDriverWait wait1 = new WebDriverWait( driver , 60 );
wait1.until(
ExpectedConditions.invisibilityOfElementLocated(
By.xpath( "//div[#class='Caption']" )
)
);
Here is the error I causes:
org.openqa.selenium.TimeoutException: Timed out after 60 seconds waiting for
element to no longer be visible: By.xpath: //div[#class='Caption']
Build info: version: '2.24.1', revision: '17205', time: '2012-06-19 16:53:24'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1',
java.version: '1.6.0_31'
Driver info: driver.version: unknown
at org.openqa.selenium.support.ui.FluentWait.timeoutException(
FluentWait.java:251)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:220)
at test.TaskListPage.isLoaded(TaskListPage.java:43)
at org.openqa.selenium.support.ui.SlowLoadableComponent.get(
SlowLoadableComponent.java:48)
at test.TaskListPage.<init>(TaskListPage.java:31)
at test.Form.testLogin(Form.java:153)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(
FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(
ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(
FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(
InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(
BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(
BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.internal.runners.statements.RunAfters.evaluate(
RunAfters.java:30)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
Also, this method gives a similar error:
ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
WebElement tE = driver.findElement( By.className("Caption") );
// return the invisibility instead of the visibility
return !tE.isDisplayed();
}
};
WebDriverWait w = new WebDriverWait(driver, 60);
w.until(e);
I had some success with this but it still throws an exception when the element finally becomes invisible and then bounces me out of my test case:
while (
// dialogMiddleCenterInner is a td that contains the Caption div
driver.findElement( By.className("dialogMiddleCenterInner")
).isDisplayed() ) {
System.out.println("Caption is visible. Waiting for login.");
AFormUtils.waitSeconds(2);
}
Thanks to Slanec for trying to help me. Ok, this was the answer. It seems that, whether or not I used ExpectedCondition or not, I just had to handle the exception instead of allowing it to throw, but it finally works:
try {
while (
// dialogMiddleCenterInner is a td that contains the Caption div
driver.findElement( By.className("dialogMiddleCenterInner")
).isDisplayed() ) {
System.out.println("Caption is visible. Waiting for login.");
MyUtils.waitSeconds(2);
} catch ( NoSuchElementException nse ) {
nse.printStackTrace(); // print but simulate .ignoring() by catching exception
}
invisibilityOfElementLocated(By locator)
An expectation for checking that an element is either invisible or not present on the DOM.
use instead,
presenceOfElementLocated(By locator)
An expectation for checking that an element is present on the DOM of a page.

Selenium 2 RemoteWebDriver -StaleElementReferenceException: Element specified by 'id' is no longer valid

I'm using the 2.4.0 selenium server in hub mode with two nodes each with 5 instances of Internet explorer (IE8 on win7) - this is all running on the same Win7 machine
The following code throws the exception on the final call to FindElements on the RemoteWebDriver
_driver.Navigate().GoToUrl(#"http://devrsql714/webpages/parentview.aspx");
var wait = new WebDriverWait(_driver, new TimeSpan(0, 0, 40));
wait.Until(d => d.FindElement(By.ClassName("TitleAlternative")));
Console.WriteLine(string.Format("Window title: {0}", _driver.Title));
var element = _driver.FindElementById("txtLessonID");
element.SendKeys("13814");
var button = _driver.FindElementById("btnLessonID");
button.Click();
wait = new WebDriverWait(_driver, new TimeSpan(0, 0, 40));
var link = wait.Until(d => d.Title.Contains("01652-06-A"));
Console.WriteLine(string.Format("Window title: {0}", _driver.Title));
Assert.IsTrue(_driver.Title.Contains("01652"));
Console.WriteLine(string.Format("page source: {0}", _driver.PageSource));
_driver.FindElementsByTagName("DIV");
I can see the browser load, navigate, fillin the text box and click the button - the page refreshes the title changes - the assert passes (this is running in MbUnit with Gallio)
but the subsequent call to _driver.FindElementsByTagName throws the exception below - I added waits in case that was the issue and any find elements results in the same exception
what am I doing wrong? - other properties on the driver work such as title and page source (which has the excepted content)
Note the same code but swapping the RemoteWebDriver for a local InternetExplorerDriver does not throw the exception
In both cases capabilities were set to ignore protect mode:
DesiredCapabilities capabilities = DesiredCapabilities.InternetExplorer();
capabilities.Platform = new Platform(PlatformType.Any);
capabilities.SetCapability("ignoreProtectedModeSettings", true);
Execute
OpenQA.Selenium.StaleElementReferenceException: Element specified by 'id' is no longer valid (WARNING: The server did not provide any stacktrace information)
Build info: version: '2.4.0', revision: '13337', time: '2011-08-12 09:57:13'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_20'
Driver info: driver.version: RemoteWebDriver
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebDriver.cs:line 948
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(DriverCommand driverCommandToExecute, Dictionary`2 parameters) in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebDriver.cs:line 805
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElements(String mechanism, String value) in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebDriver.cs:line 851
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementsByTagName(String tagName) in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebDriver.cs:line 622
at SeleniumTests.DemoTest.AnotherTest()
This is apparently a bug in version 2.4.0 of the selenium server. Downgrading to 2.3.0 might make the problem go away. See this thread on the selenium-users mailing list for more information.