Getting StaleElementReferenceException in an exercise | Selenium Forum
M
Posted on 21/07/2016
[code:3uqezb2b]
public class TestGoogleLinks {

public static void main(String[] args) throws InterruptedException {

WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().window().maximize();

driver.get("https://www.google.co.in");
driver.findElement(By.xpath("//input[@name='q']")).sendKeys("selenium");
driver.findElement(By.xpath("//button[@value='Search']")).click();


List<WebElement> results = driver.findElements(By.xpath("//div[@class='g']/div/h3/a"));
System.out.println(results.size());

//To click on page link upto 5 pages
int pageNum=2;
while(pageNum<=5){
//WebDriverWait wait = new WebDriverWait(driver, 30);
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//table[@id='nav']/tbody/tr/td["+pageNum+"]//following::span[1]")));
Thread.sleep(3000);
driver.findElement(By.xpath("//table[@id='nav']/tbody/tr/td["+pageNum+"]//following::span[1]")).click();
List<WebElement> temp = driver.findElements(By.xpath("//div[@class='g']/div/h3/a"));
results.addAll(temp);
pageNum++;

}

System.out.println(results.size());
for(int i=0;i<results.size();i++){

System.out.println(results.get(i).getText());
}

}

}

[/code:3uqezb2b]
At the end I am getting result.size() correctly, but the next for loop is not working

M
Replied on 21/07/2016

try these methods.

https://gist.github.com/djangofan/5112655


M
Replied on 21/07/2016

I am not getting error due to finding element, it is something related to variable 'Results'
Error:'Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 15.05 seconds'


M
Replied on 21/07/2016

above you said you're getting stale-element reference exception.


M
Replied on 24/07/2016

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: 15.14 seconds

This is the error message


M
Replied on 24/07/2016

please try the above solutions.

that is the only solution to stale elements.