2012-12-17 38 views
5

嗨我需要检查一个下拉字段有给定值,但这些值没有选择,所以它没有得到显示在下拉框中。 我具有以下的Xpath对元件Selenium.isElementPresent在Webdriver中的替代方法是什么

//table[contains(@id,'Field')]//tr[td//span[text()='Code']]/preceding-sibling::*[1]/td//select[contains(@id,'GSRCH_FLT')]/option[text()='not='] 

被正确识别在浏览器中的元素。但是,当我使用以下webdriver方法来验证它

driver.findElement(By.xpath("//table[contains(@id,'Field')]//tr[td//span[text()='Code']]/preceding-sibling::*[1]/td//select[contains(@id,'GSRCH_FLT')]/option[text()='not=']")).isDisplayed(); 

它的返回false,因为它没有显示在框中。

你能告诉我这个选择吗?

回答

8

你想:

private boolean isElementPresent(WebDriver driver, By by){ 
    return driver.findElements(by).count != 0; 
} 

findElements()是这个比findElement()更好,因为它不会等待,如果该元素不存在。如果您在启用隐式等待的情况下运行,findElement()将超时查找元素(这是您正在捕获的异常),并且需要一段时间。

+0

如果您正在测试元素是否存在,为什么返回测试等于零? –

+0

@MthetheLock DOH!谢谢,比较是颠倒的,现在已经修复了。 –

4

我发现WebDriver没有一个名为isElementPresent()的函数。这是在Selenium-1.0中使用的重要功能之一。 要在WebDriver中实现这一点,您只需编写一个如下所述的方法。然后,您可以使用此功能与任何类型的By(By.id,BY.name等)

private boolean isElementPresent(WebDriver driver, By by){ 
    try{ 
    driver.findElement(by); 
    return true; 
    }catch(NoSuchElementException e){ 
    return false; 
    } 
} 

这里是你将如何调用该函数

if (isElementPresent(by.id("btnSubmit")) { 
    // preform some actions 
} 

的一个例子如果在页面上找到该元素,上面的函数将返回true,否则它将返回false。

+1

@覆盖上面的代码更易于阅读并且可重复使用。唯一进一步的建议是改进代码包括超时。由于通常检查是出现元素是一些时间框架。用于'findElement()' - with-timeout而不是'findElements()'-with-count的 –

+0

-1。 –

0
internal static bool IsElementPresent(IWebDriver driver, By by, int timeoutSeconds=10) 
    { 

     for (int second = 0; second< timeoutSeconds ; second++) 
     { 
      try 
      { 
       driver.FindElement(by); 
      } 
      catch (NoSuchElementException e) 
      { 
       Thread.Sleep(1000); 
       continue; 
      } 

      return true; 
     } 

     return false; 

    } 
0

使用isDisplayed()用于验证元件是否可用在页面上。

相关问题