首页 > 解决方案 > 错误:过时的元素引用:当我运行表格时,元素未附加到页面文档

问题描述

我正在运行一个表,其中包含一些我需要访问的链接,获取此链接的内容,返回并继续滚动。这些链接没有“href”属性,您需要单击它们才能工作。但是当我点击它们返回并继续时,会出现这个错误:“stale element reference: element is not attach to the document page”

这是我的代码:

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

对于 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()

标签: pythonseleniumselenium-chromedriver

解决方案


stale element reference当您返回页面时找不到html文档时出现。在这种情况下,您需要再次重新初始化元素。尝试以下代码。

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)

不知道它是否对link你有帮助。但是你点击我不知道来源。你必须在循环中获取源,否则你会遇到类似的问题。


推荐阅读