selenium python onclick() 给出了 StaleElementReferenceException [英] selenium python onclick() gives StaleElementReferenceException

查看:85
本文介绍了selenium python onclick() 给出了 StaleElementReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发人员将代码更改为使用 onclick() DOM 元素而不是 url.所以现在我需要一直重新加载页面以防止它变得陈旧.我怎样才能用一个 find_elements_by_xpath 做到这一点?我假设 document.*.submit() 需要 DOM?

The developer changed the code to use an onclick() DOM element instead of an url. So Now I need to reload page all the time to prevent it from getting stale. How can I do this with a single find_elements_by_xpath? I assume it is the document.*.submit() that needs the DOM?

https://localhost:4778/ruleengine/AlarmTest?category=Alert#,文字:(力),onclick():document.Forceee0deabfba2341d2a0988779499f5530.submit()

https://localhost:4778/ruleengine/AlarmTest?category=Alert#, text:(Force), onclick():document.Forceee0deabfba2341d2a0988779499f5530.submit()

旧代码现在失败:

driver.get(alarmurl)
elems = driver.find_elements_by_xpath("//a[contains(text(), '(Force)')]")
for el in elems:
    el.click()

我目前的解决方法是在每次点击后重新加载页面,但是我们可能有 3000 个事件要删除,这使得它非常缓慢.

My current workaround is to reload the page after every click, but we may have 3000 events to remove, making it horrendously slow.

driver.get(alarmurl)
elems = driver.find_elements_by_xpath("//a[contains(text(), '(Force)')]")
while len(elems) > 0:
    driver.get(alarmurl)
    elems = driver.find_elements_by_xpath("//a[contains(text(), '(Force)')]")
    elems[0].click()

谢谢

推荐答案

如果您遇到 StaleElementReferenceException,我认为您不必重新加载整个页面,但我也可能是错的.它发生在元素不再附加到 DOM 时,再次搜索该元素以引用该元素

I dont think you have to reload the entire page if you encounter StaleElementReferenceException but I may be wrong too. It happens When the element is no longer attached to the DOM, search for the element again to reference the element

以下代码可能无法解决您的问题,但应该可以帮助您开始实施更好的解决方案

The below code may not clear your issue, but should help you start implementing a better solution

driver.get(alarmurl)
elems = driver.find_elements_by_xpath("//a[contains(text(), '(Force)')]")
for el in elems:
    try:
      el.click()
    except StaleElementReferenceException:
       # find the element again and click

这篇关于selenium python onclick() 给出了 StaleElementReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆