selenium报错:Message: stale element reference: element is not attached to the page document

在使用selenium时,报了一个错误

 

 

 

报错的原因:

  所引用的元素已过时,不再依附于当前页面。通常情况下,这是因为页面进行了刷新或跳转

 

解决方法:

  重新定位元素

 

 

代码示例:

# 旧代码(报错)
lists = self.root.find_elements_by_xpath('/html/body/table[4]/tbody/tr[2]/td/a')
for i in lists:
    self.root.get(i.get_attribute(''href))
# 新代码(解决方法)
lists = self.root.find_elements_by_xpath('/html/body/table[4]/tbody/tr[2]/td/a')
for j in range(len(lists)):
    self.root.find_elements_by_xpath('/html/body/table[4]/tbody/tr[2]/td/a')[j].click()

 

posted @ 2020-10-23 11:14  十一的杂文录  阅读(1599)  评论(0编辑  收藏  举报