0

I know there have been several questions asked regarding stale elements, but I can't seem to resolve these. My site is private so unfortunately can't share, but seems to always throw the error somewhere within the below for-loop. This loop is meant to get the text of each row in a table (number of rows varies). I've assigned WebDriverWait commands and have a very similar for-loop earlier in my code to do the same thing in another table on the website which works perfectly. I've also tried including the link click command and table, body, and tableText definition inside the loop to redefine at every iteration.

Once the code stops and the error message displays (stale element reference: element is not attached to the page document (Session info: chrome=89.0.4389.128)), if I manually run everything line-by-line, it all seems to work and correctly grabs the text.

Any ideas? Thanks!

link = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "*link address*")))
link.click()
table = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "TableId")))
body = tableSig.find_element(By.CLASS_NAME, "*table body class*")
tableText = body.find_elements(By.TAG_NAME, "tr")
rows = len(tableText)
approvedSigs = [None]*rows

for i in range(1, rows+1):
    approvedSigs[i-1] = (tableText[i-1].text)
    approvedSigs[i-1] = approvedSigs[i-1].lstrip()
    approvedSigs[i-1] = approvedSigs[i-1][9:]
    approvedSigs[i-1] = approvedSigs[i-1].replace("\n","   ")
Retsied
  • 79
  • 8
  • 1
    sounds like it's still populating the DOM when you're looping. Either use a long enough sleep before your find_elements method, or catch the exception and run find_elements again. Check the answer here: https://stackoverflow.com/questions/66820416/random-errors-using-wait-for-element-clickable-method-in-selenium Note: The error is only thrown when using a method on the element... in your case that's the ".text" call. – pcalkins Apr 20 '21 at 20:48
  • That does seem to have done the trick! Thanks. I also looked at that link. Is there a way (instead of setting a arbitrary long sleep time, or running through a while loop like in your link) to wait until the page is static/DOM is no longer populating? – Retsied Apr 20 '21 at 21:23
  • not a good way... there are various events that fire when javascript starts processing and ends, but reading those states requires your own JS. Hard to time those things especially since JS is async by nature. Hard to get your script to run before the other, etc.. See here: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState Better to use the stale element exception itself to know when to re-gather webreferences. An alternative to while loop is to functionize your method and re-call if stale element is thrown. (with sanity count = 2 * webdriverwait timeout period.) – pcalkins Apr 20 '21 at 22:27

0 Answers0