【问题标题】:WebDriver to close popup window after certain timeWebDriver 在一定时间后关闭弹出窗口
【发布时间】:2019-04-09 14:23:05
【问题描述】:

我有一个基于Selenium WebDriver 的测试,它填写表格并将其发送以进行处理。在处理期间打开一个窗口。有时处理失败,但是这个窗口没有关闭,所以我们不能得到结果。这个测试的目的是得到结果。我尝试为此窗口设置超时,因此它应该在WebDriver 预定义的时间(我现在将其设置为 10 秒)后关闭,并且应该重新发送表单。我使用以下代码。

WebElement webElement;
try {
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.findElement(sendButton).click();
    webElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("button-resultdown")));
} catch (TimeoutException ex) {
    webElement = null;
} finally {
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
if (webElement == null) {
    driver.findElement(popUpClose).click();
    TimeUnit.SECONDS.sleep(4);
    driver.findElement(sendButton).click();
}

弹窗不会在 10 秒后自动关闭。我检查了元素定位器,它们是有效的。

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver webdriverwait


    【解决方案1】:

    最佳做法是不要同时使用显式和隐式等待,请查找更多详细信息here
    对于弹出关闭,您可以尝试使用 JavaScript 单击或等到popUpClose 可以单击。

    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    driver.findElement(sendButton).click();
    
    List<WebElement> elements = waitElements(driver, 5, By.className("button-resultdown"));
    if (elements.size() == 0){
        List<WebElement> popUpCloseButtons = driver.findElements(popUpClose);
        System.out.println("Popup Close Buttons size: " + popUpCloseButtons.size());
        if (popUpCloseButtons.size() > 0)
            js.executeScript("arguments[0].click();", popUpCloseButtons.get(popUpCloseButtons.size() - 1));
            //popUpCloseButtons.get(popUpCloseButtons.size() - 1).click();
    }
    

    以及自定义等待方法:

    public List<WebElement> waitElements(WebDriver driver, int timeout, By locator) throws InterruptedException {
        List<WebElement> elements = new ArrayList<>();
        for (int i = 0; i < timeout; i++) {
            elements = driver.findElements(locator);
            if (elements.size() > 0)
                break;
    
            System.out.println("Not!");
            Thread.sleep(1000);
        }
    
        return elements;
    }
    

    【讨论】:

    • 谢谢,但是当 WebDriver 应该关闭窗口时,我如何定义“超时”值?
    • 我应该等待一个预定义的时间,然后单击关闭按钮,然后等待窗口消失。所以这段代码错过了第一步,等待一个预定义的时间(10秒)。页面加载时按钮是可点击的,所以这不是一个好的条件。
    • 您可以在WebDriverWait wait = new WebDriverWait(driver, 10);中设置的预定义时间。 if (elements == null) 如果没有结果,请单击关闭按钮。然后等到invisibilityOfElementLocated 等待您为显式等待设置的预定义时间。如果你想点击直到弹出窗口关闭,你也可以把它放在一个循环中
    • 我试过你的代码,但它不起作用,没有任何效果。我也尝试使用ExpectedConditions.invisibilityOfElementLocated,但我在 10 秒后得到了TimeoutException,并且弹出窗口仍然打开。
    • 检查更新的代码。还要检查 DOM 中是否有多个 popUpClose 按钮​​
    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多