2014-11-24 15 views
0

場景:打開網站,獲取對Webelement「About」的引用,單擊About,再次導航並再次使用變量引用 - 導致StaleElementReference異常。這隻會發生在Selenium Java中,但是在使用Watir時,它可以正常工作。這兩個代碼片段都在下面發佈。任何人都有一個該死的線索是怎麼回事?同樣的場景 - StaleElementReferenceException與Java,但Watir很好

# Below Java code produces StaleElementReferenceException 
    public class StaleElementException { 
    public static void main(String[] args) { 
    ChromeDriver driver = new ChromeDriver(); 
    driver.get("http://seleniumframework.com"); 
    WebElement about = driver.findElementByLinkText("ABOUT"); 
    System.out.println(about.getText()); 
    about.click(); 
    driver.navigate().back(); 
    System.out.println(about.getText()); 
    } 
    } 

#Below Ruby Watir Code works fine 
    require 'watir-webdriver' 
    @browser = Watir::Browser.new :chrome 
    @browser.goto "http://seleniumframework.com" 
    about = @browser.link(text: 'ABOUT') 
    puts about.text 
    about.click 
    @browser.back 
    puts about.text 

回答

1

的Watir自動進行刷新,其中的webdriver不做陸續發現元素調用,因此您需要按照Saifur的建議。

+0

這是有趣的要注意。你知道Watir重新初始化之後的事件嗎?謝謝 – machzqcq 2014-11-29 04:00:22

+0

除非你設置Watir.always_locate = false,否則它會一直查找它。 – titusfortner 2014-11-29 10:18:07

+0

感謝您的配置設置。我可以想到其他方式可以幫助我。歡呼 – machzqcq 2014-12-02 15:44:36

1

我不知道的Watir如何在這裏工作。但是,如果您發現某個元素點擊它,則會導航到另一個頁面,並刷新其中的內容。因此,您需要返回driver.navigate().back();並嘗試使用相同的about元素來執行您的操作,該操作不再有效。刷新的DOM意味着對元素的引用丟失,這不再是有效的元素。你應該做的是在飛行中再次找到相同的元素並執行你的動作。完整的代碼看起來應該像下面這樣:

public class StaleElementException { 
     public static void main(String[] args) { 
      ChromeDriver driver = new ChromeDriver(); 
      driver.get("http://seleniumframework.com"); 
      WebElement about = driver.findElementByLinkText("ABOUT"); 
      System.out.println(about.getText()); 
      about.click(); 
      driver.navigate().back(); 
      System.out.println(driver.findElementByLinkText("ABOUT").getText()); 
     } 
    } 

注:在最後一行的變化

+0

是的我明白,DOM刷新,但不應該與Watir發生這也是我的問題? – machzqcq 2014-11-24 16:18:43

+0

很難說,因爲我從來沒有使用過Watir。不同的工具有它自己的方式來處理這種情況 – Saifur 2014-11-24 16:24:43