Selenium:处理加载屏幕遮挡Web元素。 (JAVA)

时间:2013-06-23 09:32:56

标签: java selenium webdriver selenium-webdriver

我正在为网页编写自动化测试用例。这是我的情景。 我必须在html表单中单击并键入各种Web元素。但是,有时在文本字段上键入时,会出现ajax加载图像,模糊我想要与之交互的所有元素。所以,我在点击下面的实际元素之前使用网络驱动程序等等,

WebdriverWait innerwait=new WebDriverWait(driver,30);
innerwait.until(ExpectedConditions.elementToBeClickable(By.xpath(fieldID)));
driver.findelement(By.xpath(fieldID)).click();

但是wait函数返回元素,即使它被另一个图像模糊并且不可点击。但click()会抛出异常

Element is not clickable at point (586.5, 278).
Other element would receive the click: <div>Loading image</div>

在每次与任何元素交互之前,是否必须检查加载图像?(我无法预测加载图像何时出现并雾化所有​​元素。) 有没有有效的方法来处理这个? 目前我正在使用以下功能等到加载图像消失,

public void wait_for_ajax_loading() throws Exception
{
    try{
    Thread.sleep(2000);
    if(selenium.isElementPresent("id=loadingPanel"))
    while(selenium.isElementPresent("id=loadingPanel")&&selenium.isVisible("id=loadingPanel"))//wait till the loading screen disappears
    {
         Thread.sleep(2000);
         System.out.println("Loading....");

    }}

    catch(Exception e){
        Logger.logPrint("Exception in wait_for_ajax_loading() "+e);
        Logger.failedReport(report, e);
        driver.quit();
        System.exit(0);
    }

}

但我不知道何时调用上述函数,在错误的时间调用它将失败。有没有有效的方法来检查元素是否实际上是可点击的?或加载图像?

谢谢..

1 个答案:

答案 0 :(得分:2)

鉴于您描述的情况,您被迫验证以下两种情况之一:

  1. 您要点击的元素是否可点击?
  2. 阻止点击仍然存在的原因是什么?
  3. 通常,如果WebDriver能够找到该元素并且它是可见的,那么它也是可点击的。知道可能会阻止它的可能原因,我宁愿选择验证这些原因。此外,它在测试代码中更具表现力:你可以清楚地看到你在等待什么你正在检查什么然后点击元素,而不是检查“可点击性”,没有明显的理由。我认为它可以让一个人(他们阅读测试)更好地理解实际上(或可能是)实际发生的事情。

    尝试使用此方法检查加载图像是否存在:

    // suppose this is your WebDriver instance
    WebDriver yourDriver = new RemoteWebDriver(your_hub_url, your_desired_capabilities);
    
    ......
    // elementId would be 'loadingPanel'
    boolean isElementNotDisplayed(final String elementId, final int timeoutInSeconds) {
        try {
            ExpectedCondition condition = new ExpectedCondition<Boolean>() {
                @Override
                public Boolean apply(final WebDriver webDriver) {
                    WebElement element = webDriver.findElement(By.id(elementId));
                    return !element.isDisplayed();
                }
            };
            Wait w = new WebDriverWait(yourDriver, timeoutInSeconds);
            w.until(condition);
        } catch (Exception ex) {
            // if it gets here it is because the element is still displayed after timeoutInSeconds
            // insert code most suitable for you
        }
            return true;
    }
    

    也许您需要对代码进行一些调整(例如,在页面加载时查找元素并仅检查它是否显示)。

    如果你不确定加载图像到底是什么时候出现的(尽管我猜你这样做了),你应该在每次点击由于加载图像而变得“无法点击”的元素之前调用此方法。如果加载图像存在,该方法将在消失后立即返回true;如果它没有在'timeoutInSeconds'时间内消失,则该方法将执行您选择的操作(例如,使用特定消息抛出异常)。

    你可以把它包起来像:

    void clickSkippingLoadingPanel(final WebElement elementToClick) {
        if (isElementNotDisplayed('loadingPanel', 10)) {
            elementToClick.click();
        }
    }
    

    希望它有所帮助。

相关问题