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

后端 未结 6 1325
深忆病人
深忆病人 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:22

    There is no such a good idea to have following scenario :

    for (WebElement element : webDriver.findElements(locator.getBy())){
      element.click();
    }
    

    Why? Because there is no guarantee that the element.click(); will have no effect on other found elements, so the DOM may be changed, so hence the StaleElementReferenceException.

    It is better to use the following scenario :

    int numberOfElementsFound = getNumberOfElementsFound(locator);
    for (int pos = 0; pos < numberOfElementsFound; pos++) {
      getElementWithIndex(locator, pos).click();
    }
    

    This is better because you will always take the WebElement refreshed, even the previous click had some effects on it.

    EDIT : Example added

      public int getNumberOfElementsFound(By by) {
        return webDriver.findElements(by).size();
      }
    
      public WebElement getElementWithIndex(By by, int pos) {
        return webDriver.findElements(by).get(pos);
      }
    

    Hope to be enough.

提交回复
热议问题