【发布时间】:2015-10-20 15:45:24
【问题描述】:
如果我的问题听起来很重要,我提前道歉,我是 QA 和 Selenium 的新手。
我正在使用Java和Selenium编写一个测试,有时我需要等待一个web元素可以访问,下面是我以前使用的sn-p代码:
int counter = 0;
while (true) {
counter++;
boolean breakIt = false;
try {
WebElement element= driverChrome.findElement(By.xpath("bla bla"));
element.click();
breakIt = true;
} catch (Exception e) {
Thread.sleep(1000);
}
if (breakIt) {
break;
}
if (counter > 4) {
System.out.println("Failed");
tearDown();
System.exit(1);
}
}
但现在我在某个地方看到了这个:
WebDriverWait wait = new WebDriverWait(driverChrome, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("bla bla"))).click();
当然第二个要短得多,但我不知道它是否更好,换句话说,它们有什么不同吗?如果是,如何?哪个更适合哪些用途?
【问题讨论】:
-
使用 WebDriverWait 总是优于 sleep 语句的理想选择。一旦元素被加载,它就会立即变得难以处理,而不是等待一段时间。特别是如果您有许多使用相同步骤的测试,从长远来看,它可以节省大量时间。
-
@AutomatedOrder 感谢您的回复,您能否将其发布为答案?如果你知道,你能告诉我在哪里可以了解更多关于 ExpectedConditions 的信息。方法?
标签: java selenium selenium-webdriver selenium-chromedriver