2012-06-11 65 views
3

我正在用Java中的Selenium FirefoxDriver開發一個測試單元。我想要一些幫助處理頁面加載。我的問題是等待元素,但仍然有一個超時。我已經嘗試過申請pageLoadTimeoutimplicitlyWait沒有成功,有些方法會繼續等待整頁加載。我的代碼預覽:Java Selenium等待元素超時

(...) 
    FirefoxDriver driver= new FirefoxDriver(firefoxProfile); 
    driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS); 
    driver.manage().timeouts().implicitlyWait(1, TimeUnit.MILLISECONDS); 
    try { 
     driver.get("http://mysite"); 
    } catch (org.openqa.selenium.TimeoutException e) { 
     //after 1 milisecond get method timeouts 
    } 
    for (int i = 0; i < 5; i++) {//5 seconds wait 
      if (driver.findElements(By.id("wait_id")).size() == 0) { //findElements cause java to wait for full load 
       debug("not found");//never happens because 'if' condition waits for full load 
       driver.wait(1000); 
      } else { 
       debug("found"); 
       break; 
      } 
     } 

在此先感謝。

+0

我猜你運行你的Firefox [不穩定加載策略(http://code.google.com/p/selenium/wiki/FirefoxDriver#-Beta-_load_fast_preference),對不對?在這種情況下,我猜這是行不通的,因爲功能是測試版,不完整和Firefoxy專用。 = /但我們會看到,也許有人對此持有一些看法。 –

+0

不,我沒有使用該配置文件pref ...我會稍後嘗試併發布結果。 – Ciro

+0

但似乎符合我的目標。發佈作爲答案,我可以給你信用。 – Ciro

回答

0

pageLoadTimeout()方法只適用於Firefox運行"unstable load strategy"。因此,運行FirefoxDriver這樣的:

FirefoxProfile fp = new FirefoxProfile(); 
fp.setPreference("webdriver.load.strategy", "unstable"); 
WebDriver driver = new FirefoxDriver(fp); 

注意,它只是Firefox的下工作,真的是不穩定的,並且可以使你的一些其他的測試失敗。謹慎使用。

0

driver.get是一個阻塞調用,並等待頁面加載。 由於您將超時設置爲1毫秒,因此引發了超時異常。 如果您將e.printStackTrace();放在您的org.openqa.selenium.TimeoutException遊艇區塊中,您可以看到它。

將超時設置爲-1。

+0

是'wait'給出錯誤,但改變並不能解決真正的問題。 – Ciro

+0

確定除了'Thread.sleep(1000);' 設置超時適用於我。 請參閱我編輯的答案。 – VolkerK

1
public static WebElement waitForElement(WebDriver driver, By by) { 

    WebElement element = null; 
    int counter = 0; 
    while (element == null) { 
     try { 
      Thread.sleep(500); 
      element = driver.findElement(by); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     if (counter > 119) { 
      System.out.println("System has timed out"); 
     } 
        counter++; 
    } 
    return element; 
相關問題