2013-11-26 46 views
1

我目前正在尝试使用硒进行一些用户界面测试,并且我遇到了这个不错的方法(不知道我从哪里得到它)..它假定照顾不存在要素和隐藏要素......selenium ElementNotVisibleException无法捕捉到隐藏的元素

问题就出在第二个陷阱:该方法保持返回“真”,即使没有显示元素/隐藏(visibility:hidden的)

public boolean elementExists(By locator, WebDriver driver) { 
    WebElement foo = null; 
    try { 
     foo = this.getElementByLocator(locator, 10, driver); 
    } catch (TimeoutException te) { 
     System.out 
       .println("Timeout - Dieses Element konnte nicht gefunden werden: " 
         + locator.toString()); 
     return false; 
    } 
    catch (ElementNotVisibleException env) { 
     System.out 
       .println("Dieses Element wurde gefunden, ist aber nicht sichtbar: " 
         + locator.toString()); 
     return false; 
    } 
    if (foo == null) { 
     return false; 
    } else { 
     return true; 
    } 
} 

public WebElement getElementByLocator(By locator, int timeout, 
     WebDriver driver) { 
    System.out.println("Rufe Methode getElementByLocator: " 
      + locator.toString()); 
    int interval = 5; 
    if (timeout <= 20) 
     interval = 3; 
    if (timeout <= 10) 
     interval = 2; 
    if (timeout <= 4) 
     interval = 1; 
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) 
      .withTimeout(timeout, TimeUnit.SECONDS) 
      .pollingEvery(interval, TimeUnit.SECONDS) 
      .ignoring(NoSuchElementException.class, 
        StaleElementReferenceException.class); 
    WebElement we = wait.until(ExpectedConditions 
      .presenceOfElementLocated(locator)); 
    return we; 
} 

任何人可以请告诉我如何修改这个以便能够识别隐藏的现有元素?提前致谢!

回答

1
ExpectedConditions.presenceOfElementLocated 

检查页面的DOM中是否存在元素。这并不一定意味着该元素是可见的。

请尝试使用visibilityOfElementLocated。这将检查元素是否存在于页面的DOM中并且可见。能见度意味着元素不仅显示,但也有一个高度和宽度大于0

更本here

catch (ElementNotVisibleException env) { 

我不认为这是在你的情况下被抛出。无论如何,如果你要与它互动,元素将被隐藏 - 这将被抛出,但不是查找。

编辑: 为什么这么多的代码很少有利?这也是一样的:

public boolean elementExists(By locator, WebDriver driver){ 
     return (new WebDriverWait(driver, 60) 
       .ignoring(NoSuchElementException.class) 
       .ignoring(StaleElementReferenceException.class) 
       .until(ExpectedConditions.visibilityOfElementLocated(locator))) != null; 
    }