Arya
Arya

Reputation: 8995

Looping through with List<WebElement> with Selenium

I get a list of anchors using the code below, and then I want to go to each link. I have came up with the code below, but after the first loop I get the following exception

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document (Session info: chrome=55.0.2883.87)

List<WebElement> listingAnchorList = driver.findElements(By.xpath("//div[contains(@class,'cat')]/a"));

for (WebElement listingAnchor : listingAnchorList) {
    driver.get(listingAnchor.getAttribute("href"));
    System.out.println(driver.getTitle());
}

Is there anyway to do this without having go to back to the page every time?

Upvotes: 1

Views: 1423

Answers (1)

Orest Savchak
Orest Savchak

Reputation: 4569

You can collect your href attributes in some new List, and then iterate over it and open each page.

Upvotes: 1

Related Questions