Problem Statement: I am getting Stale Element Exception when for loop executes the second time.
Description:
I am using for loop to handle table elements. In the first iteration, it will search for the required element on the page. If the element is not available on that page then it will go and search on the second page. Webdriver successfully finds the element if its available on the first page but if it's not available on the first page then it will look for the element on the second page. But here for loop fails with the exception called 'Stale Element Exception.
Error Message:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
Code:
List <WebElement> allAmountValues = driver.findElements(By.xpath("(//table[@width=760][@cellspacing=1])[2]/tbody/tr/td[8]/div"));
for(int i =0;i<allAmountValues.size();i++){
System.out.println("Value are : "+allAmountValues.get(i).getText().replaceAll("\\s+", " "));
}
String testValue = "100000";
System.out.println("No.of Rows in the Table : "+allAmountValues.size());
for (int i1 =1; i1<allAmountValues.size();i1++) {
String amount = allAmountValues.get(i1+1).getText().replaceAll("\\s+","");
//System.out.println("amount Values : "+amount);
System.out.println("Value are : " + allAmountValues.get(i1).getText() + "== Corresponding link is : " + clicklinks.get(i1).getText());
if (amount.equalsIgnoreCase(testValue)) {
System.out.println("Found:" +testValue);
clicklinks.get(i1).click();
waitDriver();
driver.navigate().back();
break;
}
else
{
WebElement clickNext = driver.findElement(By.xpath("//a[contains(text(), 'Next')]"));
clickNext.click();
}
}
for(int rw=2;rw<allAmountValues.size();rw++)
{
WebElement a1 = driver.findElement(By.xpath("(//table[@width=760][@cellspacing=1])[2]/tbody/tr["+rw+"]/td[8]/div/span"));
String amm = a1.getText().replaceAll("\\s+", "");
System.out.println("Current value is:" +amm);
if(amm.equalsIgnoreCase("100000"))
{
WebElement a2 = driver.findElement(By.xpath("/html/body/form/div/table/tbody/tr/td/table/tbody/tr[5]/td/table/tbody/tr["+rw+"]/td[1]/div/input[6]"));
a2.click();
break;
}
}
WebElement authoriseButton = driver.findElement(By.xpath("//input[@name='btnAuthorise']"));
if(authoriseButton.isEnabled())
{
authoriseButton.click();
}
else
{
System.out.println("Authorise Button is not enabled");
}
}
I am facing stale element error exception on :
String amount = allAmountValues.get(i1+1).getText().replaceAll("\\s+","");
this line.
Any help would be appreciated.