【问题标题】:Java Selenium wait for element with timeoutJava Selenium 等待元素超时
【发布时间】:2012-06-14 01:47:08
【问题描述】:

我正在用 Java 中的 Selenium FirefoxDriver 开发一个测试单元。我需要一些帮助来处理页面加载。我的问题是在等待元素时仍然有超时。我已经尝试应用pageLoadTimeout,implicitlyWait 没有成功,一些方法继续等待整页加载。我的代码预览:

    (...)
    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;
            }
        }

提前致谢。

【问题讨论】:

  • 我猜你确实在运行你的 Firefox with unstable loading strategy,对吧?在这种情况下,我猜它不会起作用,因为该功能是测试版,不完整且仅限 Firefoxy。 =/ 但我们会看到,也许有人对此有所了解。
  • 不,我没有使用该配置文件首选项...我稍后会尝试并发布结果。
  • 但这似乎符合我的目标。发布作为答案,以便我给你信用。

标签: java firefox selenium webdriver


【解决方案1】:

pageLoadTimeout() 方法仅适用于使用"unstable load strategy" 运行的 Firefox。因此,像这样运行FirefoxDriver

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

请注意,它只能在 Firefox 下运行,确实不稳定,并且可能会使您的其他一些测试失败。谨慎使用。

【讨论】:

    【解决方案2】:
    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;
    

    【讨论】:

      【解决方案3】:

      driver.get 是一个阻塞调用,等待页面加载。 由于您将超时设置为 1 毫秒,因此会引发超时异常。 如果您将e.printStackTrace(); 放入您的org.openqa.selenium.TimeoutException cacht 块中,您可以看到它。

      将超时设置为 -1。

      【讨论】:

      • yes wait 给出错误,但改变并不能解决真正的问题。
      • 好的,除了Thread.sleep(1000); 设置超时对我有用。查看我编辑的答案。
      猜你喜欢
      • 2016-12-25
      • 2016-07-28
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多