0

I have List of URLs and I just wanted to open the URL on same browser session. To do that I have written the below code but it is throwing the error after opening the first URL i.e. second URL is not being opened.

findElements = driver.findElements(By.xpath("//*[@id='search-user-found']//p/a"));

for (WebElement webElement : findElements) 
{
    Thread.sleep(200);
    System.out.println(webElement.getAttribute("href"));
    driver.navigate().to(webElement.getAttribute("href"));
    Thread.sleep(200);
}

Error:

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

Please assist.

Andrew Regan
  • 5,087
  • 6
  • 37
  • 73
Maskii
  • 13
  • 3

1 Answers1

0

When you navigate to another page the DOM is changing and the WebDriver is loosing the elements it previously located. That causes the StaleElementReferenceException. I suggest you save the links as strings and use them.

List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='search-user-found']//p/a"));
List<String> hrefs = new List<String>();

for (WebElement webElement : findElements) 
{
    hrefs.add(webElement.getAttribute("href"));
}

for (String href : hrefs) 
{
    Thread.sleep(200);
    System.out.println(href);
    driver.navigate().to(href);
    Thread.sleep(200);
}
Guy
  • 46,488
  • 10
  • 44
  • 88