如何使用 Selenium 命令点击警报窗口中的"确定"按钮?

seleniumautomation testingtesting tools更新于 2026/2/12 10:07:17

我们可以使用 Selenium WebDriver 点击警报窗口中的"确定"按钮。警报是在网页上设计用来通知用户或执行某些操作的。它借助 Javascript 实现。

警报可以分为三种类型:提示、确认对话框或警报。Selenium 提供多个 API 来处理带有 Alert 接口的警报。要点击警报窗口中的"确定"按钮,首先我们必须使用 switchTo().alert() 方法切换到警报窗口。

接下来,要点击"确定"按钮,我们必须使用 accept() 方法。请注意,我们无法通过检查来识别警报窗口中的元素。此外,无法为警报创建自定义 xpath。

让我们使用一个包含"确定"和"取消"按钮的示例警报。我们必须在代码中导入 org.openqa.selenium.Alert 才能使用警报。

示例

代码实现。

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.Alert;
public class AlertAccept{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // 识别元素
      driver.findElement(By.xpath("//button[@name='submit']")).click();
      // Alert 接口和 switchTo().alert() 方法
      Alert al = driver.switchTo().alert();
      // 使用 accept() 点击"确定"接受
      al.accept();
      driver.quit();
   }
}

相关文章