【问题标题】:Wait for element in webdriver等待 webdriver 中的元素
【发布时间】:2011-12-03 00:29:58
【问题描述】:

我遵循了这里写的内容: WebDriver Selenium API: ElementNotFoundErrorException when Element is clearly there !

我的代码如下:

    Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
    return new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
          }
       };
    }

   ....... 

   driver.get(baseUrl);

   WebDriverWait wait = new WebDriverWait(driver, 10);
   wait.until(presenceOfElementLocated(By.className("classname")));
   findByClassAndName(driver, "x-tree3-node-text", "Name1").click();

问题是,那似乎没有做任何事情。它不起作用,我什至看不到任何等待网页 gui 的痕迹。我通过超时的隐式等待得到了同样的结果......有人可以帮忙吗?

【问题讨论】:

    标签: webdriver selenium-webdriver


    【解决方案1】:

    您必须捕获从 ExpectedCondition 或您的 Function 抛出的 Throwables(apply() 方法是很好的地方)并 返回 null 以便 Wait.until() 继续运行 - 有关详细示例,请参阅 http://rostislav-matl.blogspot.com/2011/05/moving-to-selenium-2-on-webdriver-part.html

    【讨论】:

      【解决方案2】:

      创建函数如下:

      public void Wait (string element)          // Wait function to wait for element
              { 
                  for (int second = 0; ; second++)
                      {
                          if (second >= 60) Assert.Fail("timeout");
                          try
                          {
                              if (IsElementPresent(By.LinkText(element))) break;
                          }
                          catch (Exception)
                          { }
                          Thread.Sleep(1000);
                       }  
              }
      

      现在在你想等待元素的地方调用这个函数,如下所示:

      string element="<element name>";
              Wait(element);
      

      【讨论】:

      • 一般来说使用显式睡眠不是一个好方法,所以我尽量避免它。
      • 同意,我讨厌不得不使用整个显式睡眠。这是丑陋的,不是好的做法。但是有时,它确实可以完成工作……直到可以进行适当的修复。如果 Selenium Webdriver 有更简单的等待功能就好了:>
      猜你喜欢
      • 1970-01-01
      • 2013-09-21
      • 2012-07-28
      • 2012-03-26
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2016-07-28
      相关资源
      最近更新 更多