2011-12-16 8 views
5

セレン2を使用して、要素が古くなっているかどうかをテストする方法はありますか?セレン2を使って古くなった要素をチェックしますか?

ページ間の遷移を開始するとします(A→B)。次に、要素Xを選択してテストします。要素XがAとBの両方に存在するとします。

Xはページ遷移が起こる前にAから選択され、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 

答えて

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クラスを使用しますが、例外をよりよく処理する必要がある場合は、 このメソッド(上記を参照してください)がうまくいく可能性があります。 Rubyで

0

$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ブロックから呼び出され、要素が古くなるまで待つことができます。

関連する問題