[英]WebDriver to close popup window after certain time
我有一个基于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秒后自动关闭。 我检查了元素定位器,这些是有效的。
最佳做法是不要同时使用显式和隐式等待,请在此处找到更多详细信息。
对于弹出窗口关闭,您可以尝试使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.