KDD Expert KDD Expert - 27 days ago 6
Python Question

Element is not longer attached to the DOM

My purpose is create list of elemnets and then click on it. For the first iteration loop works perfectly, it open first link. Then it failed.

My code is :

hrefList = driver.find_elements_by_xpath(".//a[contains(text(), 'כרטיס רופא')]")

print("length of List is : " + str(len(hrefList)))

for href in hrefList:
print(href)
href.click()


I get the next error message:

selenium.common.exceptions.StaleElementReferenceException:
Message: The element reference of <a> stale: either the element is no longer attached to the DOM or the page has been refreshed

Answer Source

This error comes when element is not present in DOM. You have to come back to the main page and then click it

Try this code you will get a solution, This is java code

String URL="https://www.ida.org.il/?pageType=19&langId=1&paramIds=%2Con_321%2Con_322%2Con_354%2Con_355%2Con_320&scope=&parameterSearch=";
    WebDriver driver=new FirefoxDriver();
    driver.get(URL);
    List<WebElement> links=driver.findElements(By.xpath("//a[contains(@href, 'https://www.ida.org.il/?categoryId=96318&itemId')]"));
    System.out.println("Total links: "+links.size());
    for (int i=0;i<links.size();i++) {


     links.get(i).click();
     System.out.println(i
             +"Current URL is: "+driver.getCurrentUrl());
     driver.navigate().back();
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     links=driver.findElements(By.xpath("//a[contains(@href, 'https://www.ida.org.il/?categoryId=96318&itemId')]"));
    }