使用硒2检查过时的元素吗? [英] Check for a stale element using selenium 2?

查看:76
本文介绍了使用硒2检查过时的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用硒2,有没有办法测试元素是否陈旧?

Using selenium 2, is there a way to test if an element is stale?

假设我启动了从一页到另一页的过渡(A-> B).然后,选择元素X并进行测试.假设元素X同时存在于A和B上.

Suppose I initiate a transition from one page to another (A -> B). I then select element X and test it. Suppose element X exists on both A and B.

间歇地,在页面转换发生之前从A中选择X,直到进入B之后才进行测试,从而引发StaleElementReferenceException.很容易检查这种情况:

Intermittently, X is selected from A before the page transition happens and not tested until after going to B, raising a StaleElementReferenceException. It's easy to check for this condition:

try:
  visit_B()
  element = driver.find_element_by_id('X')  # Whoops, we're still on A
  element.click() 
except StaleElementReferenceException:
  element = driver.find_element_by_id('X')  # Now we're on B
  element.click()

但我宁愿这样做:

element = driver.find_element_by_id('X') # Get the elment on A
visit_B()
WebDriverWait(element, 2).until(lambda element: is_stale(element))
element = driver.find_element_by_id('X') # Get element on B

推荐答案

我不知道您在那里使用哪种语言,但是解决此问题所需的基本思想是:

I don't know what language you are using there but the basic idea you need in order to solve this is:

boolean found = false
set implicit wait to 5 seconds
loop while not found 
try
  element.click()
  found = true
catch StaleElementReferenceException
  print message
  found = false
  wait a few seconds
end loop
set implicit wait back to default

注意:当然,大多数人不是这样做的.人们大多数时候都使用ExpectedConditions类,但是在需要更好地处理异常的情况下 这种方法(如上所述)可能会更好.

NOTE: Of course, most people don't do it this way. Most of the time people use the ExpectedConditions class but, in cases where the exceptions need to be handled better this method ( I state above) might work better.

这篇关于使用硒2检查过时的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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