2016-12-02 96 views
1

在我们对任何Web元素执行操作以避免“NoSuchElementException”异常之前,我已经经历了许多Google答案,以确保如何确保元素可用性。Selenium WebDriver:如何确保Web页面上的元素可用性?

  1. WebDriver driver = new FirefoxDriver();
  2. driver.findElement(By.id(“userid”))。sendKeys(“XUser”);

这里线#2会抛出“” NoSuchElementException异常”,如果该元素没有可用的页面上。

我只是想避免这种异常被抛出。

有可用多种方法检查这webdriver的。

  1. isDisplayed()
  2. 的IsEnabled()
  3. driver.findElements(By.id(“userid”))。size()!= 0
  4. driver.findElement(By.id(“userid”))。size()!= null
  5. driver.getPageSource ().contains(“userid”)

这是上述方法中确保元素可用性的最佳方法之一?为什么?

除此之外还有其他方法吗?

在此先感谢。感谢您宝贵的时间。

回答

0

尝试使用显式的等待selenium API。

等待一段时间,直到您所需的元素在网页上可用。你可以试试下面的例子:

WebDriverWait wait = new WebDriverWait(driver,10); 
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("userid")))); 

所以上面的行会等待直到元素10秒,如果在不到10秒钟的可用元素,则其将停止等待,继续向前迈进执行。

1
public boolean isElementPresentById(String targetId) { 

     boolean flag = true; 
     try { 
      webDrv.findElement(By.id(targetId)); 

     } catch(Exception e) { 
      flag = false; 
     } 
     return flag; 
    } 
  • 如果元素是可用的,你会得到真正的从一个方法否则为false。
  • 所以,如果你得到错误,那么你可以避免点击该元素。
  • 您可以使用上面的代码确认元素的可用性。
0

您可以使用您的问题中列出的任何方法 - 没有最好的或最差的方法。

还有一些其他方法 - 两个由@Eby和@Umang在他们的答案中提出,以及下面的方法不等待元素,只是在这个元素存在或不存在的时候勉强:

if(driver.findElements(By.id("userid")).count > 0){ 
     System.out.println("This element is available on the page"); 
    } 
    else{ 
     System.out.println("This element is not available on the page"); 
    } 

然而一个要求是::

线#2会抛出“” NoSuchElementException异常”,如果元素不 可用的页面上。
我只想避免这种异常被抛出

然后在我看来,最简单的方法是:

try{ 
    driver.findElement(By.id("userid")).sendKeys("XUser"); 
}catch(NoSuchElementException e){ 
    System.out.println("This element is not available on the page"); 
    -- do some other actions 
} 
0

你可以写,可以在其上进行任何操作之前检查所需要的Webelement存在一个通用的方法。例如,以下方法能够基于所有支持的标准来检查Webelement的存在性,例如, XPath的,ID,名称,标记名,班级等

public static boolean isElementExists(By by){ 
    return wd.findElements(by).size() !=0; 
} 

举例来说,如果你需要找到基于其XPath中Webelement的存在,您可以在以下方式使用上述方法:

boolean isPresent = isElementExists(By.xpath(<xpath_of_webelement>); 


if(isPresent){ 
     //perform the required operation 
} else { 
     //Avoid operation and perform necessary actions 
} 
相关问题