How to fetch all links and click those links one by one using Selenium WebDriver

后端 未结 6 1328
深忆病人
深忆病人 2021-01-05 22:59

I am using Selenium WebDriver with java.

I am fetching all links from webpage and trying to click each link one by one. I am getting below error:

6条回答
  •  花落未央
    2021-01-05 23:07

    If you're OK using WebDriver.get() instead of WebElement.click() to test the links, an alternate approach is to save the href value of each found WebElement in a separate list. This way you avoid the StaleElementReferenceException because you're not trying to reuse subsequent WebElements after navigating away with the first WebElement.click().

    Basic example:

    List hrefs = new ArrayList();
    List anchors = driver.findElements(By.tagName("a"));
    for ( WebElement anchor : anchors ) {
        hrefs.add(anchor.getAttribute("href"));
    }
    for ( String href : hrefs ) {
        driver.get(href);           
    }
    

提交回复
热议问题