在编写 Selenium 测试时,我总是遇到一个问题,尝试对尚未准备好的元素进行单击可能会导致 StaleElementReference/ElementClickIntercepted 异常。如果我只等待 2 秒让某个项目可点击,那么测试会在成功的地方失败,从而使测试变得不稳定。
我已经修复了 WebElement
检索,在我认为元素丢失之前,我使用隐式等待等待元素出现大约 2 秒,并且我一直在尝试创建一个 clickElement()
函数围绕基本的 click()
函数来实现相同的目的。
其目的是不断尝试以 100 毫秒的增量进行单击,直到可以为止。我通过捕获异常并为每次点击增加计数器来实现此目的,并且只有在单击该元素或多次尝试单击引发异常时才跳出循环。
这是我写的函数:
public void clickElement(WebElement element) {
int maxTimeOut = 50;
int timeOutCt = 0;
boolean isTimedOut = false;
System.out.println("=> Try to click on <" + element.getTagName() + ">");
while ( !isTimedOut ) {
try {
element.click();
isTimedOut = true; // could click
System.out.println("\n OK \n");
} catch (Exception e) {
waitSeconds(0.1);
timeOutCt++;
System.out.println(" \t => Error while attempting to click for the " + timeOutCt +"nd time \n");
if ( timeOutCt > maxTimeOut ) {
isTimedOut = true;
fail("Element <" + element.getTagName() + "> is not clickable. See exception: " + e);
}
}
}
}
waitSeconds 是:
public void waitSeconds(double t) {
long mT = (long) (t * 1000);
try {
System.out.print("\n \t \t ( ) Sleep de " + mT + "secondes");
Thread.sleep(mT);
System.out.print(" ... Done \n ");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
我遇到的问题是,这样做似乎需要很长的时间,至少超过一毫秒,至少我可以说它持续了一秒多。
我想也许我的 waitSeconds()
函数无法正常工作,但我在一个简单的程序中测试了它,它按预期工作:waitSeconds(0.1)
结果为 100ms等等。
那么,为什么当调用 clickElement
并尝试多次单击某个元素时,两次尝试之间可能需要长达两秒的时间?
是控制台输出减慢了速度吗?
或者是 try/catch 搞乱了一切?
最佳答案
我在 try/catch 方面遇到了一些类似的问题,请尝试在 try/catch block 之前禁用隐式等待,并在 catch 之后再次启用它。希望这会有所帮助。
关于java - Selenium try/catch 点击似乎需要很长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170186/