[英]Selenium method visibilityOf - Doesn't seem to be working?
当我使用列出的方法查看某个元素是否在页面上可见时,我收到一个异常,指出它无法使用指定的定位器定位元素。
任何想法,有没有人以前遇到过这个问题,甚至有更好的方法?
public boolean isElementPresentByWebElement(WebElement element) {
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver).withTimeout(15, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
for (int i = 0; i < 2; i++) {
try {
fluentWait.until(ExpectedConditions.visibilityOf(element));
System.out.println("Element is visible: " + element.toString());
return true;
} catch (Exception e) {
System.out.println(
"Unable to locate the element: " + element.toString() + ", Exception: " + e.toString());
throw (e);
}
}
return false;
}
我认为你的代码对于你想要做的事情来说过于复杂。 有一个内置类ExpectedConditions
,可以满足您的需求。 您也在循环等待,这是不必要的。 我建议您传入定位器 ( By
) 而不是WebElement
。 它将扩展您使用此功能的能力,因为您不必在使用该功能之前找到该元素。
public boolean isElementPresentByLocator(By locator)
{
try
{
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(locator));
System.out.println("Element is visible: " + locator.toString());
return true;
}
catch (TimeoutException e)
{
System.out.println("Unable to locate the element: " + locator.toString() + ", Exception: " + e.toString());
return false;
}
}
下面的代码更像是对代码的直接翻译和简化。
public boolean isElementPresentByWebElement(WebElement element)
{
try
{
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element));
System.out.println("Element is visible: " + element.toString());
return true;
}
catch (TimeoutException e)
{
System.out.println("Unable to locate the element: " + element.toString() + ", Exception: " + e.toString());
return false;
}
}
更新 :
尝试使用以下:
int waitCounter = 0;
public static void WaitUntilVisible(WebDriver driver, WebElement element) throws InterruptedException, IOException {
try {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(elementToBeClicked));
if (!elementToBeClicked.isDisplayed()) {
System.out.println("Element not visible yet. waiting some more for " + element);
if (waitCounter < 3) {
waitCounter++;
WaitUntilVisible(element);
}
waitCounter = 0;
}
} catch (Exception e)
{
System.out.println("Handling exception");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.