2012-06-11 64 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; 
相关问题