pythonseleniumgoogle-chromestaleelementreferenceexception

Python Selenium Error - StaleElementReferenceException: Message: stale element reference: element is not attached to the page document


Today I'm having troubles due to a "a href" button that does not have any ID to be identified, then let's explain a little bit more about the problem... I have an structure like this one(let's assume XXX is an anonymous path):

wait = WebDriverWait(driver, 5)
el=wait.until(EC.presence_of_element_located((By.ID, 'XXX1')))
entries = el.find_elements_by_tag_name('tr') 
for i in range(len(entries)):   
    if(entries[i].find_element_by_xpath(XXX2).text==compare):
    el = wait.until(EC.element_to_be_clickable((By.ID,XXX3)))
    el.click()
    el=wait.until(EC.presence_of_element_located((By.ID, XXX4)))
    entries2 = el.find_elements_by_tag_name('tr')
    for j in range(len(entries2)):
        #Some statements...
    xpath = ".../a"
    your_element=WebDriverWait(driver,10)\
    .until(EC.element_to_be_clickable((By.XPATH,xpath)))##Here the problem
    your_element.click() 

Then, I'm getting information from an hibrid page (dynamic and static) using as driver a ChromeDriver one, once I get a big table, inside every row there is a button that shows more info, then I need to click it for open it too, the main problem is when this operation iterates, that error is shown by the output. This driver is a ChromeDriver one. In summary, first I search something and click on search button, then I get a table where every row(at the end in the last column) has a button that once is open, shows more information, consequently I need to open it and close it due to the next row, it works with the first row, but with the second one, it crashes. I would really appreciate any advice of how to handle this problem.

Thanks in advance!


Solution

  • The problem is that you change with the click the dom within your loop. For mr this never worked.

    One solution is, to try to re-query within the loop to make sure your at the correct position. Your third line:

    entries = el.find_elements_by_tag_name('tr')
    

    should be executed every time and with a counter make sure you are at the correct position of your <tr> entries.