0

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

} }

4

1 回答 1

1

如果我正确地跟随你,那是你的

List<WebElement> outerLIElementList = driver.findElements(By.xpath(".//* 
[@id='root']div/div[*]"));

那已经过时了。您每次都需要找到该元素。我会迭代这个列表的长度,并根据该迭代找到特定的 div。

须藤代码:

for(int child = 0; child<len(outerLIElementList); child++)
    driver.findElement(By.xpath(".//*[@id='root']div/div[{0}]", child));

等等

于 2018-07-16T20:54:58.227 回答