如何使用selenium 2验证页面上的Web元素是否存在

时间:2013-07-04 12:18:43

标签: java selenium-webdriver

我尝试使用selenium web-driver 2工具实施测试。

应用程序具有元素,其存在是不可预测的。好。在大多数情况下,它们出现在页面上。但在某些情况下,他们不是。以下方法单击不可预测的元素

public void clickTypeAheadDropdown(String typeAheadItem) {
    String xPathItemSelector = "//div[@class='gwt-SuggestBoxPopup']//td[text()='" + typeAheadItem + "']";
    WebElement dropDownItem = driver.findElement(By.xpath(xPathItemSelector));
    if (dropDownItem.isDisplayed() ) {
        dropDownItem.click();
    };

}

但是当元素不存在时它会失败。方法 driver.findElement(By.xpath(xPathItemSelector)

)提升了异常

您知道吗,我该如何测试,页面上是否有元素?

P.S。我认为,捕捉" Element Not Found"异常并不是一个好主意,因为当测试时间不足时会引发异常

3 个答案:

答案 0 :(得分:3)

我通常使用以下方法来测试元素是否存在。

public boolean isElementPresent(By element) {
   try {
       driver.findElement(element);
       return true;
   } catch (NoSuchElementException e) {
       return false;
   }
}

也可以在WebDriver

上配置等待时间
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

我不知道有任何其他方法可以做到这一点。由于您的页面可能会在不可预测的时间内加载,因此您需要等待并使用超时。

答案 1 :(得分:0)

您也可以使用FindElements:

    /// <summary>
    /// Checks if the specified element is on the page.
    /// </summary>
    public static bool IsElementPresent(this IWebDriver driver, By element)
    {
        if (driver.FindElements(element).Count > 0)
            return true;
        else
            return false;
    }

    /// <summary>
    /// Checks if the specified element is on the page and is displayed.
    /// </summary>
    public static bool IsElementDisplayed(this IWebDriver driver, By element)
    {
        if (driver.FindElements(element).Count > 0)
        {
            if (driver.FindElement(element).Displayed)
                return true;
            else
                return false;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// Checks if the specified element is on the page and is enabled.
    /// </summary>
    public static bool IsElementEnabled(this IWebDriver driver, By element)
    {
        if (driver.FindElements(element).Count > 0)
        {
            if (driver.FindElement(element).Enabled)
                return true;
            else
                return false;
        }
        else
        {
            return false;
        }
    }

希望它有所帮助。

答案 2 :(得分:0)

要检查元素是否存在,您可以使用以下代码:

if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}