0

I have a application which required selenium to navigate to next page and verify if required information found, it not found than come back to same page and than click on next user information and verify required information is found and this continue till we have users links.

My process: I have created List of all the user links to run the enhance for loop. Now, when user click on first user link and if information not found than selenium is coming back to same page, and when try to click on second user, it give exception 'org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document'. I tried using back() method but not working. Is there any work around to this?

Thanks, Karim

Karim Narsindani
  • 434
  • 3
  • 14
  • 38

3 Answers3

1

StaleElementReferenceException comes up because the DOM element was destroyed and recreated when you tried to navigate back.

Hence, I will suggest you to get all the href attributes of the user links from the original page, and navigate to each of them, rather than clicking on trying to click on link(s) one-by-one, which will throw StaleElementReferenceException always.

Below is the way to get the list of all links in the page (of course you can narrow it down the elements you need; this is just an example):

    //Getting the list of all links in the page
    List<WebElement> list = driver.findElements(By.tagName("a"));

    //Getting the "href" attribute of each elements and putting them into another list
    List<String> href_links = null;
    for(WebElement link:list){
        href_links.add(link.getAttribute("href"));
    }

    //Navigating through each links
    for(int i=0;i<href_links.size();i++){

        driver.get(href_links.get(i));
    }
Community
  • 1
  • 1
Subh
  • 4,354
  • 1
  • 13
  • 32
0

Another solution using the page objects you may have:

int numberOfLinks = page.getUserLink().size();
NextPage nextPage;
for (int i = 0; i < numberOfLinks - 1; i++) {
  page.getUserLink().get(i).click();
  nextPage = new NextPage();
  if (nextPage.isInformationFound()) {
    break;
  }
  driver.navigate().back();
  page = new Page();
}

Make the correspondent adjustments and give it a try ;)

Regards.

Marcos
  • 21
  • 1
0

The workaround which I found to this problem, as the link is generated dynamic I wont be able to get href value. However, I fetch the userid given in onclick attribute and store it in list and than i created url for those users and open in current browser. While coming back I simple click on link which navigate to same page.

Karim Narsindani
  • 434
  • 3
  • 14
  • 38