java - 如何在几秒钟内重试某些方法,当超时抛出方法的异常而不是 Selenium 中的 TimeoutException?
问题描述
我想制作一个选择元素来选择一个选项。但是页面加载时该选项可能不存在。因为选项是从数据库、API 或具有响应时间的东西加载的。
目前,我使用 selenium wait.until 和布尔条件。制作自定义等待方法。
我的解决方法:
.
.
.
String exceptionMessage;
public void myCode() throws Exception {
exceptionMessage = "";
Integer sec = 10;
WebDriverWait wait = new WebDriverWait(shared.getBrowser(), Duration.ofSeconds(sec));
try {
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
try {
.
.
.
CommonMethods.selectOption(element, optionText);
return true;
} catch (Exception e) {
exceptionMessage = e.getMessage();
return false;
}
}
});
} catch (TimeoutException e) {
throw new Exception("Timeout: [" + sec + "] seconds, Exception message: [" + exceptionMessage + "]");
}
}
如果超时,结果将是:
java.lang.Exception: Timeout: [10] seconds, Exception message: [element not visible: Element is not currently visible and may not be manipulated
有硒方法吗?还是更好的方法?
解决方案
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" xpath']")));
使用唯一的 Xpath 来查找元素,因为会有一些隐藏的元素。
如果上述等待不起作用,您也可以尝试以下方法:
new WebDriverWait(Driver,TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible("Yyour element path");
推荐阅读
- mysql - MIN 和 MAX 值的 MySql 百分比
- r - 与我自己使用类库的代码相比,KNN 重复的 cv 方法返回不合理的结果
- asynchronous - perl6 "首先等待的操作"
- video-streaming - avconv 不能覆盖文件?
- amazon-web-services - 具有公共子网和私有子网的 AWS VPC - 实例可以 ping 自己,但不能互相 ping
- python - 在熊猫数据框中查找最大值的索引
- android - 多次注入同一个作用域对象实例
- css - 如何使用css制作带有狗骨轮廓的按钮?
- ios - 为什么每当玩家向左或向右时它只播放我的左侧动画?
- java - 通过流转换数组数组