我希望使用 selenium 关闭父窗口上的弹出窗口。我正在使用java。
到目前为止,我正在循环浏览页面上的所有 DIV,直到看到“关闭”文本(带有关闭文本的按钮),然后如果找到关闭,则单击关闭按钮,但这需要时间,因为它会遍历所有 DIV。
当前代码:
// Find the visible element that has text 'Close' and click on it
WebElement closeButton = Functional
.getVisibleElement(pDriver.findElements(By.xpath("//span[contains(.,'Close')]")));
if (closeButton != null) {
closeButton.click();
public static WebElement getVisibleElement(List<WebElement> pListOfElements) {
for (int i = 0; i < pListOfElements.size(); i++) {
if (pListOfElements.get(i).isDisplayed()) {
for (int a = 0; a <= ATTEMPT; a++) {
try {
return pListOfElements.get(i);
} catch (StaleElementReferenceException e) {
LOGGER.info("attempting to press the element. Amount of attempt: " + ATTEMPT);
}
}
} else {
}
}
return null;
}
有什么办法可以关闭 Selenium 中的弹出窗口吗?
最佳答案
如果您想接受警报弹出窗口并根据需要传递超时(例如:4000(4 秒)),请尝试此方法
public static void acceptAlertIfAvailable(long timeout) {
//log.info("Checking if there is a popup alert to accept it");
long waitForAlert = System.currentTimeMillis() + timeout;
boolean boolFound = false;
do {
try {
Alert alert = driver.switchTo().alert();
if (alert != null) {
String alertMsg = alert.getText();
alert.accept();
//log.info("Pop-up alert [" + alertMsg + "] was found and accepted");
boolFound = true;
}
} catch (NoAlertPresentException ex) {
//log.error("Pop-up alert Not handled and Exception occured --> " + ex.getMessage());
}
} while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
}
如果您想消除警报,请尝试以下方法:
public static void dismissAlertIfAvailable(long timeout) {
//log.info("Checking if there is a popup alert to dismiss it");
long waitForAlert = System.currentTimeMillis() + timeout;
boolean boolFound = false;
do {
try {
Alert alert = driver.switchTo().alert();
if (alert != null) {
String alertMsg = alert.getText();
alert.dismiss();
//log.info("Pop-up alert [" + alertMsg + "] was found and dismissed");
boolFound = true;
}
} catch (NoAlertPresentException ex) {
//log.error("Pop-up alert Not handled and Exception occured --> " + ex.getMessage());
}
} while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
}
关于java - 关闭 selenium java 中的弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50624770/