0

I'm running a table that has some links that I need to access, grab the contents of this link, go back and keep scrolling. These links do not have the "href" attribute, you need to click on them to work. But when I click on them to go back and keep going, this error occurs: "stale element reference: element is not attached to the document page"

This is my code that does this:

tb = driver.find_elements_by_tag_name('table')[1] tbody = tb.find_elements_by_tag_name('tbody')[0]

for row in tbody.find_elements_by_xpath('./tr'): cols = row.find_elements_by_xpath('./td')

link = cols[0].find_elements_by_tag_name('a')[0]
link.click()
time.sleep(4)

lines_extract = driver.find_elements_by_tag_name('tbody')[0].find_elements_by_xpath('./tr')

for le in lines_extract:
    td_num_doc = le.find_elements_by_xpath('./td')[0]
    print(td_num_doc)
    div_link_back = driver.find_elements_by_tag_name('div')[2]
    div_link_back.find_elements_by_tag_name('a')[0].click()
Lucas
  • 1
  • 1
    It looks like your loop is likely the problem. You’ve defined lines_extract and therefore each element in lines_extract on one page, and go to a different page, it appears, on the last pine of the loop. Then if the loop iterates you make another reference to an le element, which is now “stale” ie no longer attached to the DOM since you navigated away from the page where you defined it. I don’t know how exactly you want to solve that problem but I’m pretty sure that’s what’s causing the error. – C. Peck Mar 27 '19 at 16:23

1 Answers1

0

stale element reference comes when the html document not found when you do page back.In that case you need to re-initialize elements again.Try the following code.

link = cols[0].find_elements_by_tag_name('a')[0]
link.click()
time.sleep(4)

lines_extract = driver.find_elements_by_tag_name('tbody')[0].find_elements_by_xpath('./tr')

for le in range(len(lines_extract)):
    link = cols[0].find_elements_by_tag_name('a')[0]
    link.click()
    time.sleep(4)
    lines_extract = driver.find_elements_by_tag_name('tbody')[0].find_elements_by_xpath('./tr')
    td_num_doc = lines_extract[le].find_elements_by_xpath('./td')[0]
    print(td_num_doc)
    div_link_back = driver.find_elements_by_tag_name('div')[2]
    div_link_back.find_elements_by_tag_name('a')[0].click()
    time.sleep(4)

Not sure if it helps you.However link you are clicking i don't know the source.You have to take the source as well inside loop otherwise you will get similar problem.

KunduK
  • 32,888
  • 5
  • 17
  • 41