2015-09-25 43 views
1

雖然關於JavaScript組件即時得到點擊:元件不連接到頁面文檔

org.openqa.selenium.StaleElementReferenceException:陳舊元件 參考:元件未連接到頁面文檔

解決這個問題的一種方法是在短時間內停止腳本: Thread.sleep(200);

我有我的10秒implicitlyWait集,我覺得有wasnt這樣的問題與舊硒

但有沒有其他辦法可以做到在全球範圍呢?

但是在這中間我已經把睡覺的,使其工作:

driver.findElement(By.cssSelector("button.btn.btn-default")).click(); 
Thread.sleep(200); 
     driver.findElement(By.xpath("//div[@id='content']/div/form")).click(); 
Thread.sleep(200); 
     driver.findElement(By.linkText("Order")).click(); 

回答

1

在我的示例中將getWebDriver()替換爲您的驅動器實例。

最佳做法是首先聲明&驗證是否存在該特定的 元素。如果你看到函數 assertAndVerifyElement()---它連續檢查5 秒的元素,然後相應地斷言它。

package com.stackoverflow; 

import org.openqa.selenium.By; 
import org.testng.Assert; 
import org.testng.annotations.Test; 

import com.services.Init; 

public class Issue3 extends Init { 

    @Test 
    public void solutionOfIssue() throws InterruptedException { 

     /* 
     * The best thing is to first assert & verify that, that particular 
     * element is present or not. if you see function 
     * assertAndVerifyElement() --- it continuously checks for element for 5 
     * secs and then assert it accordingly. 
     */ 

     assertAndVerifyElement(By.cssSelector("button.btn.btn-default")); 
     getWebDriver().findElement(By.cssSelector("button.btn.btn-default")).click(); 

     assertAndVerifyElement(By.xpath("//div[@id='content']/div/form")); 
     getWebDriver().findElement(By.xpath("//div[@id='content']/div/form")).click(); 

     assertAndVerifyElement(By.linkText("Order")); 
     getWebDriver().findElement(By.linkText("Order")).click(); 

    } 

    public void assertAndVerifyElement(By element) throws InterruptedException { 
     boolean isPresent = false; 

     for (int i = 0; i < 5; i++) { 
      try { 
       if (getWebDriver().findElement(element) != null) { 
        isPresent = true; 
        break; 
       } 
      } catch (Exception e) { 
       // System.out.println(e.getLocalizedMessage()); 
       Thread.sleep(1000); 
      } 
     } 
     Assert.assertTrue(isPresent, "\"" + element + "\" is not present."); 
    } 

} 

希望這會爲你工作。:)

1

爲了避免這種情況,你應該重新定位的元素。獲得元素後,其Java對象的引用可能會變陳舊。再次執行如下操作: WebElement element = WebDriver.findElement(By by)

編輯:對於您的例子試試這個

driver.findElement(By.cssSelector("button.btn.btn-default")).click(); 
//30s timeout, use timeout not sleep 
WebDriverWait wait = new WebDriverWait(driver, 30); 
By xpath = By.xpath("//div[@id='content']/div/form") 
//wait for element to be clickable, then click 
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(xpath)); 
element.click(); 
1

你的問題是,你需要構建測試用例更好的和/或缺乏,你是如何在網站上自動作品的理解指標。特別是

用一段時間停止腳本:Thread.sleep(200);

被認爲是一個非常糟糕的做法。不管你做什麼都不要混合隱式和顯式等待,事情會開始出錯,顯式等待是recommended solution

如果(因爲它似乎是你的情況)頁面正在被AJAX操作修改,等待頁面加載將不起作用。不要等待頁面加載,而是等待您測試的條件變爲真實。這樣,你給AJAX操作時間執行,如果你有問題,當超時發生時你會得到一個錯誤。

StaleElementReferenceException是由DOM找到元素後刷新 造成的。請記住,WebElement是頁面上特定元素的參考 ,如果DOM get的refresed此參考被破壞,並且您需要再次找到元素以便能夠與 進行交互。