Selenium方法visibilityOf - 似乎没有工作?

问题描述 投票:-1回答:2

当我使用列出的方法来查看元素是否在页面上可见时,我得到一个异常,说明它无法使用指定的定位器找到元素。

任何想法,有没有人面对这个问题,甚至有更好的方法?

    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;
}

enter image description here

java selenium selenium-webdriver webdriver
2个回答
1
投票

我认为你的代码对于你想要做的事情来说过于复杂。有一个内置的类,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;
    }
}

-1
投票

更新 :

尝试使用以下:

 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");
}
}
© www.soinside.com 2019 - 2024. All rights reserved.