隐式等待和显式等待没有解决Selenium Webdriver with Java中的问题

时间:2011-11-28 12:24:18

标签: java selenium selenium-webdriver

我一直在测试涉及多个ajax调用的应用程序,因此我需要等待条件,以便在进行ajax调用后元素存在/可见。我使用了implicitwaitexplicitwait两种方法,但它们似乎都不适用于我,因为生成了一个或另外一个例外,如下所示:

1.无法找到元素

2.Element已禁用,因此不能用于操作

隐式等待使用如下:

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
WebElement we = driver.findElement(By.name("q"));

问题: 当我测试此代码时,在浏览器打开后,它会在2秒内抛出异常。

  

结果:生成异常

显式等待

WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/3); 
WebElement element = wait.until(presenceOfElementLocated(By.name("q"));

问题:

当我测试此代码时,浏览器打开后,它会在2秒内抛出异常

  

结果:生成了异常。

还使用了visibilityOfElementLocated,但它对我不起作用。


有人遇到过这个问题,还是有人为此解决了问题?

1 个答案:

答案 0 :(得分:0)

我不能说我之前遇到过这个问题,但我也写了自己的自定义DOM轮询类。这就是我的工作。

private int Timer = 180;

private bool CheckForElement(WebDriver driver,string byType,string selector)
{
  bool elementFound = false;

  for (int i = Timer - 1; i > 0; i--)
   {
       if (!itemFound)
       {
          Thread.Sleep(1000); //sets the loop to check every second this can be done at a much faster or slower rate depending on your preferences
          if (byType.ToLower() == "id")
          {
           try{
               WebDriver element = driver.FindElement(By.Id(selector);
               if(element.Displayed)
               {
                   elementFound = true;
               }
           }
           catch {
               //Do Nothing Here as we don't need to handle the exception
           }
          }
          else if (byType.ToLower() == "tagname")
          {
           try{
               WebDriver element = driver.FindElement(By.TagName(selector);
               if(element.Displayed)
               {
                   elementFound = true;
               }
           }
           catch {
               //Do Nothing Here as we don't need to handle the exception
           }
          }
          else if (byType.ToLower() == "cssselector")
          {
           try{
               WebDriver element = driver.FindElement(By.cssSelector(selector);
               if(element.Displayed)
               {
                   elementFound = true;
               }
           }
           catch {
               //Do Nothing Here as we don't need to handle the exception
           }
          }
          else if (byType.ToLower() == "classname")
          {
           try{
               WebDriver element = driver.FindElement(By.ClassName(selector);
               if(element.Displayed)
               {
                   elementFound = true;
               }
           }
           catch {
               //Do Nothing Here as we don't need to handle the exception
           }
          }
      }
      else
      {
          i = 0; //stops the loop when the element is found
      }
   }

  return elementFound ;
}