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

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.

Related

handling calendar in selenium

whenever my code is executing it is getting navigating to some other page. My code is of how to handle with calendar in selenium.
please help
package basic;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class calender {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new ChromeDriver();
//Launching website
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.path2usa.com/travel-companions");
//selecting dates
driver.findElement(By.xpath("//*[#id=\"travel_date\"]")).click();
while(!driver.findElement(By.cssSelector("[class='datepicker-days'] th[class='datepicker-switch']")).getText().contains("April"))
{
driver.findElement(By.cssSelector("[class='datepicker-days'] th[class='next']")).click();
}
List<WebElement> dates = driver.findElements(By.className("day"));
//grab common attribute // put into list and iterate
int count = driver.findElements(By.className("day")).size();
for(int i=0;i<count;i++)
{
String text = driver.findElements(By.className("day")).get(i).getText();
if(text.equalsIgnoreCase("23"))
{
driver.findElements(By.className("day")).get(i).click();
break;
}
}
}
}
starting ChromeDriver 73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72) on port 13761
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Apr 01, 2019 9:38:18 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Cannot locate an element using css selector=[class='datepicker-days'] th[class='datepicker-switch']
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'Nilufars-MacBook-Air.local', ip: '2405:204:4383:7327:1104:ad36:576:9d64%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_201'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:327)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:420)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:431)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at basic.calender.main(calender.java:23)
Welcome to SO.
You can directly select the date as shown below.
driver.findElement(By.xpath("//input[#name='travel_date']")).sendKeys("25 May 2019");
This way you will save your execution time by ignoring the month loop and date loop.
Simplified code:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.path2usa.com/travel-companions");
//selecting the date
driver.findElement(By.xpath("//input[#name='travel_date']")).sendKeys("25 May 2020");
//continue your test with next steps
// quit the driver.
driver.quit();

How to send text to the username and password field within the webpage throug Safari Browser and selenium-webdriver

I am trying to login to the webpage for which I am supposed to write test scripts. But the login script fails each time in Safari, although the same script runs well on Chrome.
Error message displayed:
Sep 10, 2018 10:55:06 AM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.id: mfacode)
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:05:20.749Z'
System info: host: 'iMac.localdomain', ip: 'fe80:0:0:0:1c2b:a0b9:a043:3a94%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.safari.SafariDriver
Capabilities {applicationCacheEnabled: true, browserName: safari, cleanSession: true, cssSelectorsEnabled: true, databaseEnabled: true, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: false, nativeEvents: true, platform: MAC, platformName: MAC, rotatable: false, version: 13605.3.8, webStorageEnabled: true}
Session ID: E2219A59-8EEE-4380-93B6-77A7DDE289BE
*** Element info: {Using=id, value=mfacode}
The script I am using:
public class LoginSafari {
public static void main(String[] args) {
System.setProperty("webdriver.safari.driver", "/usr/bin/safaridriver");
WebDriver driver= new SafariDriver();
driver.get("https://yapiapp.io/welcome");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOfElementLocated(By.className("auth0-lock-input"))).sendKeys("alaka.goswami#*****.com");
driver.findElement(By.name("password")).sendKeys("*******");
driver.findElement(By.className("auth0-lock-submit")).click();
// WebDriverWait wait=new WebDriverWait(driver, 40);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("******")));
// username and password masked//
Is there any way to get passed this or solve this?
This error message...
Sep 10, 2018 10:55:06 AM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.id: mfacode)
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. (WARNING: The server did not provide any stacktrace information)
...implies that the WebDriver instance was unable to find any element as per the Locator Strategy you have used.
You need to take care of a couple of things as follows:
Different browser renders the HTML DOM different so you need to construct Locator Strategies to work Cross Browser.
As the username/email and your password field both are on the same page you have to induce WebDriverWait only once.
As you need to invoke sendKeys() method so instead of ExpectedConditions as visibilityOfElementLocated() you need to use the elementToBeClickable() method.
Your effective code block will be:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class yapiapp_login {
public static void main(String[] args) {
System.setProperty("webdriver.safari.driver", "/usr/bin/safaridriver");
WebDriver driver = new SafariDriver();
driver.manage().window().maximize();
driver.get("https://yapiapp.io/welcome");
new WebDriverWait(driver, 30).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.auth0-lock-input[name='username ']"))).sendKeys("alaka.goswami#*****.com");
driver.findElement(By.cssSelector("input.auth0-lock-input[name='password']")).sendKeys("Alakananda Goswami");
}
}
Browser Snapshot(with GeckoDriver/Firefox):

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

Webdriver: Tests crash with internet explorer7 with error Modal dialog present

Following tests is automated by using java and selenium-server-standalone-2.20.0.jar.
The test crashes with the error:
Page title is: cheese! - Google Search
Starting browserTest
2922 [main] INFO org.apache.http.impl.client.DefaultHttpClient - I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server failed to respond
2922 [main] INFO org.apache.http.impl.client.DefaultHttpClient - Retrying request
Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Modal dialog present (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.20 seconds
Build info: version: '2.20.0', revision: '16008', time: '2012-02-27 19:03:04'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_24'
Driver info: driver.version: InternetExplorerDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:170)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:129)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:438)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:139)
at org.openqa.selenium.ie.InternetExplorerDriver.setup(InternetExplorerDriver.java:91)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:48)
at com.pwc.test.java.InternetExplorer7.browserTest(InternetExplorer7.java:34)
at com.pwc.test.java.InternetExplorer7.main(InternetExplorer7.java:27)
Test Class:
package com.pwc.test.java;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import com.thoughtworks.selenium.Selenium;
public class InternetExplorer7 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver webDriver = new HtmlUnitDriver();
webDriver.get("http://www.google.com");
WebElement webElement = webDriver.findElement(By.name("q"));
webElement.sendKeys("cheese!");
webElement.submit();
System.out.println("Page title is: "+webDriver.getTitle());
browserTest();
}
public static void browserTest() {
System.out.println("Starting browserTest");
String baseURL = "http://www.mail.yahoo.com";
WebDriver driver = new InternetExplorerDriver();
driver.get(baseURL);
Selenium selenium = new WebDriverBackedSelenium(driver, baseURL);
selenium.windowMaximize();
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("passwd"));
WebElement signInButton = driver.findElement(By.id(".save"));
username.sendKeys("myusername");
password.sendKeys("magic");
signInButton.click();
driver.close();
}
}
I don't see any modal dialog when I launched the IE7/8 browser manually. What could be causing this?
You may take a screenshot by webDriver to see the modal dialog when this Exception occurs.
I was also getting the same exception on Firefox. I observed that the username and password fields were autocompleted because the option "Remember passwords for sites" was enabled in Firefox. So, while recording even if I erase the contents and enter, it would not record the data entered. I disabled the option and rerecorded my test case. Now, it works fine.
Hope it helps.

Selenium WebDriver Getting Error:java.net.SocketException: Connection reset

I am getting the following error
Just to add this code was working fine earlier. I havent changed anything. The firefox browser open but nothing happens. I can see webdriver written in bottom right.
Exception in thread "main" org.openqa.selenium.WebDriverException: java.net.SocketException: Connection reset
Build info: version: '2.4.0', revision: '13337', time: '2011-08-12 09:57:13'
System info: os.name: 'Windows Vista', os.arch: 'x86', os.version: '6.0', java.version: '1.7.0'
Driver info: driver.version: FirefoxDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:404)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:106)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:89)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:127)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:78)
at org.openqa.selenium.example.GetAllOptionInDropdown.main(GetAllOptionInDropdown.java:13)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:130)
at org.apache.http.impl.io.SocketInputBuffer.fillBuffer(SocketInputBuffer.java:127)
at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:233)
at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:98)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:210)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:271)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:233)
at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:209)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:292)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:126)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:483)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.openqa.selenium.remote.HttpCommandExecutor.fallBackExecute(HttpCommandExecutor.java:274)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:254)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:125)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.execute(FirefoxDriver.java:257)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:387)
... 5 more
Code Throwing Error:
package org.openqa.selenium.example;
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 GetAllOptionInDropdown {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in/advanced_search");
List<WebElement> element = driver.findElements(By.xpath("//div/table[2]/tbody/tr[3]/td/select/option"));
System.out.println("Total DropDown Options "+ element.size());
for (WebElement webElement : element) {
System.out.println(webElement.getText());
}
driver.quit();
}
}
I made a same mistake by thinking that 2.9 was the latest version. After updating the version 2.25 from 2.9 my coding is working fine.
:)
Try updating your gecko driver
I had the same problem using the chrome driver. It worked yesterday, today it didn't.
For reasons I don't understand, it worked after updating my chrome driver to the latest version. (2.25 instead of 2.9. Earlier I made the mistake of thinking 2.9 was the latest).