WebDriver how to check if an element exists?

Causes : do things recently from a UI Automation registered, may not be met with page elements using WebDriver problems in the process, because the element is not present, then perform operations related elements when it will wait for the timeout and throw an exception, so in order to deal with does not exist, it is to use a try / catch a way to deal with it, if there is no try in, then execute the code logic catch.

try {
    driver.findElement(By.id("element_a")).click();
} catch (NoSuchElementException e) {
    driver.findElement(By.id("element_b")).click();
}

The code above problems:

1、 Code unsightly
2、When using try / catch if the element is not present, the waiting time is very long, it takes about 30 seconds, so speed is really affect the efficiency

Thinking:

真的只有使用try / catch 唯一可能的方式?

Solution:

You may be used driver.findElements( By.id("element") ).size() != 0to determine whether the element is present, to avoid try / catch, efficient code

// 设置超时等待为0毫秒
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
boolean elementExists;
// 利用seiz()方法来判断元素是否存在
elementExists = driver.findElements( By.id("element_a") ).size() != 0;
if(elementExists){
	driver.findElement(By.id("element_a")).click();
}else{
	driver.findElement(By.id("element_b")).click();
}
// 重新设置默认的超时等待时间
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Guess you like

Origin blog.csdn.net/weixin_44290425/article/details/90203637