0

On my page, I have 25 Links displayed inside a web table, now i have to traverse all pagination pages, like 1-25, 25-50, 50-75 etc...my specific link text can be in any pagination set, it can be on any page.

  <<previous |1 - 25 of 125| next>>

If the link text matches my string, then click otherwise keep on clicking on "next" button until i find the link. Problem is i am getting "org.openqa.selenium.StaleElementReferenceException: stale element reference: stale element not found

as the Webelement is not longer in DOM. I have tried few methods but its not working.

Method 1:

List<WebElement> links = new ArrayList<WebElement>();
links = driver.findElements(By.xpath("//table[contains(@id,'table1')]//tr//a"));
if (links.get(i).getText().equalsIgnoreCase(MatchString)) {
    links.get(0).click();
    break;
}
driver.findElement(By.linkText("next")).click();

}

Method2:

for (int i = 1; i < links.size(); i++) {
////            links = driver.findElements(By.xpath("//table[contains(@id,'table1')]//tr//a"));
//          links = new ArrayList<WebElement>();
//          links = driver.findElements(By.tagName("a"));
//          driver.navigate().refresh();
//
//
//          if (links.get(i).getText().trim().equalsIgnoreCase(MatchString.trim())) {
//              links.get(i).click();
//              System.out.println("Link is clicked");
//              break;
//          }
//
//          else {
//              driver.findElement(By.linkText("next")).click();
//
//          }
//      }

1 Answer 1

0

You can try this:

while(!isTheRightPage(MatchString)) {
   clickOnTheNextButton();
}

clickOnThePageLink();

Additionally, you can surround this code with a try-catch in case you never find the page that matches MatchString.

clickOnTheNextButton would be straight forward:

driver.findElement(By.linkText("next")).click();

And isTheRightPage would be:

return driver.findElement(PATH_TO_THE_LINK).getText().equalsIgnoreCase(MatchString)

If you can't locate the link directly, you can look for the link that is visible:

val listOfLinks = driver.findElements(PATH_TO_THE_LIST_OF_LINKS)
val visibleLink = listOfLinks.filter(link -> list.isVisible()).findFirst()
return visibleLink.equalsIgnoreCase(MatchString)
2
  • this solution is not working...link with matching string is not getting clicked.
    – arvind2359
    Commented May 11 at 8:30
  • Can you share the code you are running? Can you share error you see? Commented May 13 at 7:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.