Webdriver is not detecting when a web element becomes invisible - selenium

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.

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.

How to deal with parent and child iframes

I have a scenario where I 1st iframe (i.e parent iframe) which has one button on it and clicking on it another iframe gets open (child iframe). I am able to switch to Parent iframe but when I click on button and tries to interact with Child iframe I'm not able to do it. Can you suggest what should be the better approach to get this type of scenarios working?
My Script:
public class Iframe {
public static void main (String []args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", Constants.Chrome_Driver);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://automation.cloudaccess.host/administrator");
driver.findElement(By.id("mod-login-username")).sendKeys("admin");
driver.findElement(By.id("mod-login-password")).sendKeys("admin#123");
driver.findElement(By.id("mod-login-password")).submit();
driver.findElement(By.linkText("Components")).click();
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.linkText("Messaging"))).build().perform();
driver.findElement(By.linkText("New Private Message")).click();
driver.findElement(By.className("wf-editor-header")).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#id=\"jform_message_imgmanager\"]"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[contains(#src,'&plugin=imgmanager')]")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"browser-actions\"]/a[#id=\"help\"]"))).click();
driver.switchTo().defaultContent();
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#id=\"mce_inlinepopups_50_ifr\"]")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"imgmanager.insert\"]/i[#class=\"icon-file\"]"))).click();
driver.quit();
}
}
Error:
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for frame to be available: By.xpath: //iframe[#id="mce_inlinepopups_50_ifr"] (tried for 20 second(s) with 500 milliseconds interval)
at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:81)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:271)
at testScripts.Iframe.main(Iframe.java:51)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //iframe[#id="mce_inlinepopups_50_ifr"]
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T15:15:08.936Z'
System info: host: 'vowellt4', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-24-generic', java.version: '1.8.0_171'
Driver info: driver.version: unknown
at org.openqa.selenium.support.ui.ExpectedConditions.lambda$findElement$0(ExpectedConditions.java:896)
at java.util.Optional.orElseThrow(Optional.java:290)
at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:895)
at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:44)
at org.openqa.selenium.support.ui.ExpectedConditions$17.apply(ExpectedConditions.java:517)
at org.openqa.selenium.support.ui.ExpectedConditions$17.apply(ExpectedConditions.java:513)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:248)
... 1 more
Just after click on help button , you can try with this code :
driver.switchTo().defaultContent();
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[src^='/administrator/index.php?option=com_jce&view=help&tmpl=component&lang=en&section=editor&category=imgmanager&']")));
You are using //iframe[#id=\"mce_inlinepopups_50_ifr\"] this xpath to switch to frame but the problem is the id is getting generated dynamically , so we do not know what will be the id every time we visit the page through automation.
I have simply converted that xpath to a valid and reliable css selector and it is working extremely good at my end.
In case you want to have xpath :
//iframe[contains(#src,'/administrator/index.php?option=com_jce&view=help&tmpl=component&lang=en&section=editor&category=imgmanager&')]
Hope this will help.
After clicking on the help button, you need to switch to the default content from the parent iframe and then need to navigate to the respective child frame.
Child Frame Xpath needs to be changed as below
Xpath: //*[#class='mceModalContainer']//div[#id='mce_inlinepopups_45_content']//iframe
Modified Working Code:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"browser-actions\"]/a[#id=\"help\"]"))).click();
driver.switchTo().defaultContent();
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//*[#class='mceModalContainer']//div[#id='mce_inlinepopups_45_content']//iframe")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id='help-menu']//*[#id=\"imgmanager.insert\"]/i[#class=\"icon-file\"]"))).click();

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.

selenium: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException:

I am working on clicking on the navigation links(marked as 1,2,...Next) for a particular search in the site dice.com
When I run the below mentioned code, it is executed once and then displays StaleElementReferenceException
Request you to help in resolving this issue
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Ex2 {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://dice.com");
driver.findElement(By.xpath("//input[#id='FREE_TEXT']")).sendKeys("Selenium");
driver. findElement(By.xpath("//*[#id='searchSubmit']")).click();
//block that has navigation links
WebElement b=driver.findElement(By.xpath("//*[#id='yui-main']/div/div[1]/div[1]/div[1][#class='pageProg']"));
//navigation links
List<WebElement> allLinks=b.findElements(By.tagName("a"));
System.out.println("Total links -->" + allLinks.size());
for(int i=0;i<allLinks.size();i++){
allLinks.get(i).click();
Thread.sleep(5000);
}
}
}
The error displayed is
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 59 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.35.0', revision: '8df0c6b', time: '2013-08-12 15:43:19'
System info: os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.2', java.version: '1.7.0_11'
Session ID: 0410f597-c149-46b5-a2b7-e84c61cc73f1
The issue is when you click the first link, the page is reloaded, and the reference Selenium has to the page becomes stale. I think this approach will work for you instead:
List<WebElement> allLinks=b.findElements(By.tagName("a"));
System.out.println("Total links -->" + allLinks.size());
String[] linkText = new String[allLinks.size()];
for(int i=0;i<allLinks.size();i++)
{
linkText[i] = allLinks.get(i).text;
}
for(int i=0;i<linkText.length;i++)
{
findElements(By.linktext(linkText).click();
Thread.sleep(5000);
}
use this as a work around
try{
//Your code which causes exception
}
catch(org.openqa.selenium.StaleElementReferenceException e){
//Repeat the code in try
}
Reason for exception is because javascript has loaded the element one more time with same name or id or whatever and you are still referring to element which is not present now.

Selenium WebDriver: Random Error determining if element is visible

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;
}
});