Quikr : Element not found exception while accessing 2nd link | Selenium Forum
M
Posted on 07/02/2016
Hi,
I tried for exercise "Click on every link one by one - Qukir.com".

Quikr.com : Able to click on first link back and then come and get stopped with exception "org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up" (but able to read all links names without clicks). Also tried to use webdriverwait for alerts to handle new popup window but not succeeded.

Can you please check following code and let me know the reason or suggests me better way:

import java.util.List;
import java.util.concurrent.TimeUnit;

//import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.ExpectedConditions;
//import org.openqa.selenium.support.ui.WebDriverWait;

public class QuickrClickLink {

public static void main(String[] args) {

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

driver.navigate().to("http://www.quikr.com");

driver.findElement(By.className("bodynew"));

driver.findElement(By.xpath(".//*[@id='csclose']/strong")).click();

/* WebDriverWait wait = new WebDriverWait(driver,20);

wait.until(ExpectedConditions.alertIsPresent());

driver.switchTo().alert().accept();

driver.switchTo().defaultContent();
*/

driver.findElement(By.xpath(".//*[@id='main-container']/div[3]/div[2]"));
List<WebElement> links= driver.findElements(By.className("CategoryName"));
System.out.println(links.size());

for(int i=0;i<links.size();i++){
String linkname= links.get(i).getText();
System.out.println(i+" : "+linkname);

links.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();

//driver.findElement(By.className("bodynew"));

driver.findElement(By.xpath(".//*[@id='csclose']/strong")).click();

}


}

}

M
Replied on 09/02/2016

First of all lets be clear about what a WebElement is.

A WebElement is a reference to an element in the DOM.

A StaleElementException is thrown when the element you were interacting is destroyed and then recreated. Most complex web pages these days will move things about on the fly as the user interacts with it and this requires elements in the DOM to be destroyed and recreated.

When this happens the reference to the element in the DOM that you previously had becomes stale and you are no longer able to use this reference to interact with the element in the DOM. When this happens you will need to refresh your reference, or in real world terms find the element again.


and use this q/a http://stackoverflow.com/questions/4846454/selenium-webdriver-staleelementreferenceexception