Home > Software engineering >  Element is not attached to the page document
Element is not attached to the page document

Time:12-12

I am trying to loop over the elements and click at them. At each click it goes to the new page, then I want to go back and click at the next element but then it raises an error cause the element is stale. I can declare an index variable and increase it over each iteration then refresh the page, find those elements again and access them by index, but what is the most efficient way to resolve this?

links = link_grid.find_elements(By.CSS_SELECTOR, "div:nth-child(1)")
            
for link in links:
       link.click()
       sleep(1)
       driver.back()
       sleep(1)

CodePudding user response:

By navigating to another page all collected by selenium web elements (they are actually references to a physical web elements) become no more valid since the web page is re-built when you open it again. To make your code working you need to collect the links list again each time. This should work:

links = link_grid.find_elements(By.CSS_SELECTOR, "div:nth-child(1)")
            
for link in links:
    link.click()
    sleep(1)
    driver.back()
    links = link_grid.find_elements(By.CSS_SELECTOR, "div:nth-child(1)")
  • Related