Can we Traverse on another page when executing foreach loop?

Viewed 146

There is Table on the page, I do need to retrieve information row by row. That is handle by for-each. Execution on same page for retrieving information is working fine.


But, Can we handle Detail page of particular Row ? Here "Test 1" has its own detail page. There are some operation which need to handle on detail page. How can we manage it and get back to actual execution.

As of now I am dealing it with for-each loop, and getting StaleElementReferenceException which is correct as webElement lost its actual ListElement<WebElement>

List<WebElement> findList = driver.findElements(By.xpath("//a[@class='*****']));

    for (WebElement webElement : findList) {
     ...
    //detail page is access by clicking webElement
    webElement.click();

    findList = driver.findElements(By.xpath("//a[@class='*****']));
    }

If there is any way, Please suggest. Thanks.

3 Answers

You can do something like this :

List<WebElement> findList = driver.findElements(By.xpath("//a[@class='*****']));
for(int i = 1 ; i<=findList.size() ; i++){

   driver.findElement(By.xpath("(//a[@class='***'])[" + i + "]")).click();
   // extract some data from next page which is invoked by clicking on Test1 hyperlink.
}  

in this way every time you are looking for //a[@class='***'][i] web element i , starting from 1 and till the end point.

P.S : You need to check this in devtool //a[@class='***'][1], whether it indicates the Test1 hyperlink or not.

Hope this helps.

Try to collect urls to detail pages of all and then open them.

There are two scenarios i can think of :

  1. Clicking the link e.g. Test1 opens a new tab :

    • In this case you can just switch to new tab inside your loop , finish your operation on this tab and finally close the second tab / switch to first tab before continuing with your next iteartion. This should also not cause StaleElementException.
  2. Clicking the link e.g. Test1 redirects to some other url in same tab :

    • For each iteration of loop, click on target link , perform some operation on new page.Before you continue with next iteration , Navigate to page containing your table again and lookup all the row elements again. Now , for next iteration you won't get StaleElementException. You will want to use the for loop so that you can maintain the index outside instead of a foreach variant.

findList = driver.findElements(By.xpath("//a[@class='*****']))

I would recommend the first option since that would be more clean and you can perform a shift + click on your link e.g. Test1 to force it open in a new tab instead of redirecting in same page. You can perform a shift + click using "Actions api" available in Selenium.

Related