智能等待,try catch方法智能定位需添加等待的元素
常用的三种等待
- 强制等待
Thread.sleep(3000);
- 隐式等待
//隐式等待 10秒
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
- 显示等待
//显式等待
long time = 10;
//element是变量
new WebDriverWait(driver.getDriver(), time).until(ExpectedConditions.visibilityOf(element));
三种等待依然不够给力
上面的三种方法可以解决大部分的等待问题,但是很多时候要用强制等待的时候不好掌握时长的设置,设短了还会报错,影响调试步骤,设长了影响执行效率,那么此时可以利用下面封装的click的方法,智能等待,根据输出结果合理添加等待时长,不影响写代码的进度
代码语言:javascript复制 public void clickname(String ele) throws InterruptedException {
List<WebElement> elelist = elements(ByMethon.bystr(ele));//获取该名称对应的列表
WebElement element = null;
long time = 3;
if (elelist.isEmpty()) {
Thread.sleep(800);
elelist = elements(ByMethon.bystr(ele));
if (!elelist.isEmpty()) {
element = elelist.get(0);//获取该名称对应的第一个元素
element.click();
}
else {
driver.refresh();
clickname(ele);
System.out.println("========================" ele " 未找到,重新执行========================");
}
} else {
element = elelist.get(0);//获取该名称对应的第一个元素
try {
Thread.sleep(200);
element.click();
} catch (WebDriverException e) {
Thread.sleep(1500);
autoScreenShot.ScreenShot("等待时长不足");
Log.warn("======" ele " 二次执行操作,建议加时等待==========");
try {
element.click();
} catch (Exception e1) {
driver.refresh();
Thread.sleep(100);
Log.warn("======" ele " 刷新一次,建议检查页面==========");
Thread.sleep(1500);
try {
elelist = elements(ByMethon.bystr(ele));
element=elelist.get(0);
element.click();
} catch (Exception e2) {
Thread.sleep(1500);
element.click();
System.out.println("第三次执行");
}
}
}
}
}
代码语言:javascript复制public static By bystr(String PropertiesKey){
String PropertiesPath = "LoginElement.properties";
//创建ReadProperties对象
ReadProperties properties = new ReadProperties(PropertiesPath);
String value = properties.getValue(PropertiesKey);
//对value进行拆分
String LocateMethod = value.split("<>")[0];
String LocateEle = value.split("<>")[1];
//System.out.println(LocateMethod "=========" LocateEle);
if(LocateMethod.equalsIgnoreCase("id")){
return By.id(LocateEle);
}else if(LocateMethod.equalsIgnoreCase("name")){
return By.name(LocateEle);
}else if(LocateMethod.equalsIgnoreCase("tagNmae")){
return By.tagName(LocateEle);
}else if(LocateMethod.equalsIgnoreCase("linkText")){
return By.linkText(LocateEle);
}else if(LocateMethod.equalsIgnoreCase("xpath")){
return By.xpath(LocateEle);
}else if(LocateMethod.equalsIgnoreCase("cssSelector")){
return By.cssSelector(LocateEle);
}else{
return By.partialLinkText(LocateEle);
}
}
执行结果如下图