【问题标题】:Selenium WebDriver : How to make sure element availability on Web Page?Selenium WebDriver:如何确保网页上的元素可用性?
【发布时间】:2017-04-16 23:34:11
【问题描述】:
在我们对任何 web 元素执行操作以避免 NoSuchElementException 异常之前,我已经阅读了许多关于如何确保元素可用性的谷歌答案。
-
WebDriver driver = new FirefoxDriver();
driver.findElement(By.id("userid")).sendKeys("XUser");
如果该元素在页面上不可用,第 2 行将抛出 NoSuchElementException。
我只是想避免抛出这个异常。
在 WebDriver 中有很多方法可以检查这一点。
isDisplayed()
isEnabled()
driver.findElements(By.id("userid")).size() != 0
driver.findElement(By.id("userid")).size() != null
driver.getPageSource().contains("userid")
在上述确保元素可用性的方法中,哪种方法最好?为什么?
除了这些还有其他方法吗?
提前致谢。感谢您宝贵的时间。
【问题讨论】:
标签:
java
selenium
testing
automation
webdriver
【解决方案1】:
public boolean isElementPresentById(String targetId) {
boolean flag = true;
try {
webDrv.findElement(By.id(targetId));
} catch(Exception e) {
flag = false;
}
return flag;
}
- 如果元素可用,您将从方法中获得 True,否则为 false。
- 因此,如果您得到 false,那么您可以避免点击该元素。
- 您可以使用上述代码确认元素的可用性。
【解决方案2】:
尝试使用 selenium API 的显式等待。
等待一段时间,直到您需要的元素在网页上可用。你可以试试下面的例子:
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("userid"))));
所以上面一行将等待元素直到 10 秒,如果元素在不到 10 秒内可用,那么它将停止等待并继续执行。
【解决方案3】:
您可以使用问题中列出的任何方法 - 没有最好或最差的方法。
还有一些其他方法 - @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
}
【解决方案4】:
您可以编写一个通用方法,该方法可以在对其执行任何操作之前检查所需 Web 元素的存在。例如,以下方法能够根据所有支持的标准检查 Web 元素的存在,例如xpath、id、name、tagname、class 等
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
}