有没有一种方法可以测试元素是否存在?任何findElement方法都会以异常结束,但这不是我想要的,因为元素可能不存在,这没有关系,这不是测试失败,所以异常不是解决方案。
我找到了这篇文章:Selenium c# Webdriver: Wait Until Element is Present,但这篇文章是为C#写的,我不太擅长。有人能把代码翻译成Java吗?很抱歉,伙计们,我在Eclipse中尝试过,但是我不能正确地在Java代码中使用它。
代码如下:
public static class WebDriverExtensions{
public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){
if (timeoutInSeconds > 0){
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}
}
发布于 2012-10-24 17:56:40
如果一个私有方法简单地查找元素并确定它是否存在,情况会是这样的:
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
这将是非常简单的,并且可以完成工作。
编辑:您甚至可以更进一步,接受一个By elementLocator
作为参数,如果您想通过id以外的其他东西来查找元素,则消除了问题。
发布于 2013-01-05 02:24:24
我发现这适用于Java:
WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.until( ExpectedConditions.presenceOfElementLocated(by) );
driver.FindElement(by);
发布于 2011-11-09 06:17:25
public static WebElement FindElement(WebDriver driver, By by, int timeoutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.until( ExpectedConditions.presenceOfElementLocated(by) ); //throws a timeout exception if element not present after waiting <timeoutInSeconds> seconds
return driver.findElement(by);
}
https://stackoverflow.com/questions/7991522
复制相似问题