如何使用 WebDriver 检查警报是否存在?
seleniumautomation testingtesting tools更新于 2026/2/11 15:22:17
我们可以使用 Selenium WebDriver 检查警报是否存在。警报是通过 JavaScript 创建的。我们将在同步中使用显式等待概念来验证警报是否存在。
我们来考虑下面的警报,并检查它是否在页面上存在。其中有一个名为 alertIsPresent 的条件,我们将使用它来检查警报是否存在。它应等待 指定的警报时间,超过该时间后将抛出异常。
我们需要导入 org.openqa.selenium.support.ui.ExpectedConditions 和 org.openqa.selenium.support.ui.WebDriverWait,以合并预期条件和 WebDriverWait 类。

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class VerifyAlert{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// 识别并点击提交
WebElement t = driver.findElement(By.name("submit"));
t.click();
// 显式等待 alert 条件
WebDriverWait w = new WebDriverWait(driver, 5);
//alertIsPresent() 条件已应用
if(w.until(ExpectedConditions.alertIsPresent())==null)
System.out.println("Alert not exists");
else
System.out.println("Alert exists");
driver.close();
}
}
输出


