How to resolve, Stale element exception? if element is no longer attached to the DOM?

后端 未结 7 1206
盖世英雄少女心
盖世英雄少女心 2020-11-30 23:01

I have a question regarding \"Element is no longer attached to the DOM\".

I tried different solutions but they are working intermittent. Please suggest a solution th

7条回答
  •  广开言路
    2020-11-30 23:17

    If you are trying to Click on link, that taking you to new page. After that navigating back and clicking on other links. They below code may help you.

    public int getNumberOfElementsFound(By by) {
        return  driver.findElements(by).size();
      }
    
    public WebElement getElementWithIndex(By by, int pos) {
        return driver.findElements(by).get(pos);
      }
    
    /**click on each link */
    public void getLinks()throws Exception{
    try {
    List componentList = driver.findElements(By.tagName("a"));
    System.out.println(componentList.size()); 
    
        for (WebElement component : componentList)
        {
            //click1();
            System.out.println(component.getAttribute("href"));
        }
     int numberOfElementsFound = getNumberOfElementsFound(By.tagName("a"));
    for (int pos = 0; pos < numberOfElementsFound; pos++) {
         if (getElementWithIndex(By.tagName("a"), pos).isDisplayed()){
    
      getElementWithIndex(By.tagName("a"), pos).click();
      Thread.sleep(200);
      driver.navigate().back();
      Thread.sleep(200);                                                       
    }
      }
        }catch (Exception e){
            System.out.println("error in getLinks "+e);
        }
    }
    

提交回复
热议问题