Python 使用selenium 2检查是否有过时的元素?

Python 使用selenium 2检查是否有过时的元素?,python,selenium-webdriver,Python,Selenium Webdriver,使用selenium 2,是否有方法测试元素是否过时 假设我启动了从一个页面到另一个页面的转换(a->B)。然后我选择元素X并测试它。假设元素X同时存在于A和B上 间歇性地,在页面转换发生之前从A中选择X,直到转到B之后才进行测试,从而引发StaleElementReferenceException。检查这种情况很容易: try: visit_B() element = driver.find_element_by_id('X') # Whoops, we're still on A

使用selenium 2,是否有方法测试元素是否过时

假设我启动了从一个页面到另一个页面的转换(a->B)。然后我选择元素X并测试它。假设元素X同时存在于A和B上

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

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

我不知道你在那里使用的是什么语言,但解决这个问题的基本思路是:

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类,但在需要更好地处理异常的情况下 这种方法(我上面提到)可能会更好。

在Ruby中

$default_implicit_wait_timeout = 10 #seconds

def element_stale?(element)
  stale = nil  # scope a boolean to return the staleness

  # set implicit wait to zero so the method does not slow your script
  $driver.manage.timeouts.implicit_wait = 0

  begin ## 'begin' is Ruby's try
    element.click
    stale = false
  rescue Selenium::WebDriver::Error::StaleElementReferenceError
    stale = true
  end

  # reset the implicit wait timeout to its previous value
  $driver.manage.timeouts.implicit_wait = $default_implicit_wait_timeout

  return stale
end
上面的代码是由提供的stalenessOf方法的Ruby翻译。类似的代码可以用Python或Selenium支持的任何其他语言编写,然后从WebDriverWait块调用以等待元素过时