自己写的Selenium查找元素等待demo
由于很多时候,做UI自动化的时候,都会有那种要稍等一下才会显示出来的元素,其实Selenium是支持显示/隐式等待的,但是感觉并不是很适合自己,我没看过其中的源码,只是根据自己的思路写了一查找元素等待的工具类其中的一个方法
package app.utils;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UIUtils {
public static Logger logger = LoggerFactory.getLogger(UIUtils.class);
public static void waitByXpath(WebDriver driver, String xpath,int seconds,int everyFindTime) throws InterruptedException,NoSuchElementException {
//计算需要查询的次数
int count = ((seconds - 1 )/ everyFindTime) + 1;
while (count > 0) {
try {
Thread.sleep(1000*everyFindTime);
// seconds = seconds - everyFindTime;
count--;
driver.findElement(By.xpath(xpath));
} catch (NoSuchElementException e) {
if (count <= 0){
logger.error("最后一次查找,没找到,请检查页面...");
throw new NoSuchElementException(Xpath);
}
logger.error("本次查找未找到元素,还将继续查找"+count+"次,"+everyFindTime+"S之后将再次查找...");
continue;
}
logger.info("元素已找到,停止等待...");
break;
}
}
}
入参:
dirver : selenium的driver
seconds : 想要等待的时间(S)
xpath : 查找元素的Xpath表达式
everyFindTime : 每几秒查询一次
这只是一个demo。其实还可以改成获取title,找ID,css样式等等方式来做元素查找的等待,代码基础不好,所以只能写的简单粗暴一些