2011-12-16 89 views
5

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

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

间歇性地,在页面转换发生之前X会从A中选择,而在进入B之后才会测试X,引发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 

回答

1

我不知道你使用的是有什么语言,但你为了解决所需要的基本思路这是:

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类,但是在需要更好地处理异常的情况下,此方法(上述状态)可能会更好。

0

在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 

上面的代码是由ExpectedConditions提供的stalenessOf方法的红宝石翻译。类似的代码可以用Python或Selenium支持的任何其他语言编写,然后从WebDriverWait块调用,直到元素过时。

相关问题