我是 selenium 新手(但经验丰富的 java 开发人员)。
我正在使用如下所示的内容:
WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));
//if search an agreement is not show up, then click on other menu, then click it back
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]")).click();
// click on search an agreement
try {
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
action = new Actions(pDriver);
action.moveToElement(searchBasket).build().perform();
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search a product')]")));
searchproduct.click();
} catch (TimeoutException e) {
}
其中 pWait 是:
WebDriverWait wait = new WebDriverWait(driver, 15);
但是,当我运行测试用例时,出现以下错误:
Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"}
Command duration or timeout: 4 milliseconds
我认为在抛出此异常之前应该等待至少 15 秒。从上面的日志来看,它只在 4 毫秒内抛出了异常。 我可以在控制台上看到,一旦到达该行,就会抛出异常。
我将隐式等待设置为 0 并使用显式等待。
我在这里错过了什么吗?
此外,在显式和隐式等待中,是达到那么多时间还是确切那么多时间, 例如,如果我将隐式等待设置为 10 秒,那么这是否意味着等待确切的 10 秒或最多等待 10 秒(如果找到元素则继续,即使元素在第 6 秒找到)
上面的显式等待也一样吗?
请帮忙
最佳答案
让我们分析一下代码中发生了什么。
我们定义了两个 WebElements
searchBasket 和 searchproduct 如下:
WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));
我们没有尝试立即在代码中使用这些 WebElement,因此没有影响。
接下来,我们为 WebElement
尝试了 WebDriverWait,如下所示:
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
我们再次没有捕获结果的返回类型
,因此没有影响。
现在,在 try{}
block 中,我们再次尝试了WebDriverWait:
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
但是我们还没有捕获/操作结果的返回类型
。这就是我们继续前进的原因:
action.moveToElement(searchBasket).build().perform();
searchBasket 引用了我们之前存储的 WebElement
:
WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
由于第一个搜索结果(没有WebDriverWait)可能根本没有返回任何WebElement
并且返回了Null。
最后,导致错误的最重要因素无法定位元素:{"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"} 是,
WebDriverWait 实例处于等待
。我们一直尝试使用 pWait
wait
因此,由于所有这些原因,WebDriverWait 从未在我们的代码中正确实现。
<小时/>混合ImplicitWait和ExplicitWait
Selenium Documentation明确提到以下内容:
WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.
关于java - Selenium隐式和显式等待,未找到超时异常元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47673679/