我有一个代码片段,如下所示。在我列出之前,我想让你知道
waitForXPathVisibility(错误,秒,睡眠,单位,xpath);
与a基本相同
WebDriverWait wait = new WebDriverWait(driver, seconds * 1000, sleep * 1000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
“error”是超时时打印的错误消息。所以我有代码
try {
waitForXPathVisibility("applicationStatusTab", seconds, 10, TimeUnit.SECONDS, APP_STATUS_TAB_SELECTED_X);
} catch (Throwable ex) {
// There seems to be some sort of problem with it not waiting the full amount
// or throwin an error when there is not, so check for that.
System.out.println("Timout After: " + new Date() + " ... This may NOT be an actual error:");
if (!isXPathDisplayed(APP_STATUS_TAB_SELECTED_X)) {
throw ex;
}
}
我们告诉它什么时间单位使用。我已指定秒数。
现在页面需要很长时间才能加载。没有尝试,页面可能会等待大约90秒左右,并抛出超时错误。我添加了catch,现在它捕获它并且没有给出错误,因为xpath即使它超时并且sait它不是:
WARNING: WebDriverException thrown by findElement(By.xpath:
//div[@id='pt1:r1']//a[contains(@id,'disAcr') and
contains(text(),'Application Status') and contains(@class,'Selected') ])
org.openqa.selenium.TimeoutException: timeout
但是,isXPathDisplayed()成功。 (此方法基本上采用xpath,执行findElementsBy()并验证大小至少为1。
我想知道的是,由于页面需要很长时间才能显示,所以当查找操作时,它会在页面显示在Chrome之前找到该元素。 (之前我已经看到页面代码可用并准备就绪,但有时需要Chrome一段时间才能更新显示)。
所以也许wait()中的find找到元素并退出,但由于页面还没有显示在终端上,否则其他人可能认为该元素不在那里并抛出错误。
这有意义吗?您可以发出某种等待,等待Chrome显示屏与Selenium正在查看的代码相匹配吗?还是我在错误的树上吠叫?
顺便说一句,即使我抓住了错误,仍会显示堆栈回溯,尽管捕获成功并且程序继续。
哦,这是Eclipse与Eclipse,Selenium和Chrome的Java。
您需要考虑以下因素:
waitForXPathVisibility (error, seconds, sleep, unit, xpath);
看起来像是我的开销。基本上没有必要在WebDriverWait
上编写单独的包装函数。waitForXPathVisibility (error, seconds, sleep, unit, xpath);
与WebDriverWait
相同。让我们来看看WebDriverWait
。WebDriverWait
根据WebDriverWait
目前对Selenium v3.8.1
的实施,构造函数如下:
WebDriverWait(WebDriver driver, Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
WebDriverWait(WebDriver driver, long timeOutInSeconds)
WebDriverWait将忽略NotFoundExceptio
条件中默认遇到的until
n实例。WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis)
WebDriverWait将忽略NotFoundException
条件中默认遇到的until
实例。根据你的问题,几乎不清楚为什么你需要像waitForXPathVisibility (error, seconds, sleep, unit, xpath);
这样的函数:
error
- until
条件将始终忽略NotFoundException
(错误)seconds
- long timeOutInSeconds
本身可用。sleep
- long sleepInMillis
可用。xpath
- 哪些可以传递给ExpectedConditions
。正如你提到的page takes a long time to load
和wait maybe 90 seconds
,WebDriverWait
如果以这种方式配置也不会抱怨。
现在,如果不查看代码或相关的HTML
,就很难进一步分析。但有几点:
xpath
在逻辑上是正确的,但性能会很差。我们总是可以构建一个更好的xpath
org.openqa.selenium.TimeoutException: timeout
异常可以阻止以下任何ExpectedConditions
:
elementToBeClickable(By locator)
elementToBeSelected(By locator)
elementSelectionStateToBe(By locator, boolean selected)
org.openqa.selenium.TimeoutException: timeout
后,元素也可见。因此isXPathDisplayed()
成功没有任何可见性你的下一个行动发布WebDriverWait
一个简单的解决方案是:
wait time
设置为120秒。Polling
设置为1000毫秒ExpectedConditions
设置为elementToBeClickable(通过定位器)