Reputation: 51
Use case:
Click button on page It open a new div popup (which has all this parent -> child - subchild heirarchy inorder to select template - There can be n number of child and subchilds) Iterate to select each subchild - but have other steps to follow post selecting each child For e.g. Have to click add on div popup , enter name for page on small popup that shows up after it, click Add and then navigate to the earlier page (with herirachy) again to select the next sub child Now, it gives Stale element reference exception
Inorder to avoid stale element exception, tried with while loop (along with try and catch) to attempt atleast twice for the child selection step and now it executes but in each loop it always selects first child - Note, it doesnt enter the try catch loop again.
Code for reference
public static void selectpage(){
driver.findElement(By.xpath(".//[@id='root']/div[2]/
div/div[1]/span[2]")).click();
driver.findElement(By.xpath(".//*
[@id='root']/div[2]/div[1]/span/span")).click();
}
public void pageLayout() throws InterruptedException {
selectpage();
List<WebElement> outerLIElementList = driver.findElements(By.xpath(".//*
[@id='root']/div/div[1]/div/div[*]"));
System.out.println(outerLIElementList.size());
// iterate through the rows in the outer element
for (WebElement outerLIElement : outerLIElementList) {
// find the inner table rows using the outer table row
List<WebElement> innerLIElementList =
outerLIElement.findElements(By.xpath("//div[2]/div[*]/section"));
System.out.println(innerLIElementList.size());
// iterate through the inner table rows and sysout
for (WebElement innerLIElement : innerLIElementList) {
Thread.sleep(5000);
int attempts = 0;
while (attempts<2){
try {
Actions builder = new Actions(driver);
builder.moveToElement(innerLIElement).build().perform();
System.out.println(innerLIElement.getText());
builder.moveToElement(innerLIElement).click(innerLIElement);
builder.perform();
break;
}
catch (StaleElementReferenceException e){
}
attempts++;
}
driver.findElement(By.xpath(".//[@id='root']/div/div[2]/button[2]")).click();
driver.findElement(By.xpath(".//[@id='root']/div/div/
/div[2]/div/input")).sendKeys("Test");
driver.findElement(By.xpath(".//*[@id='root']/div/div/
/div[2]/button[2]")).click();
Thread.sleep(1000);
selectpage();
} }
Upvotes: 0
Views: 1305
Reputation: 601
If I follow you correctly it is your
List<WebElement> outerLIElementList = driver.findElements(By.xpath(".//*
[@id='root']div/div[*]"));
that goes stale. You need to find the element each time. I would iterate on the length of this list and find the specific div based on that iteration.
sudo code:
for(int child = 0; child<len(outerLIElementList); child++)
driver.findElement(By.xpath(".//*[@id='root']div/div[{0}]", child));
etc.
Upvotes: 1