如何处理 Selenium 中的警报?
我们可以使用 Alert 接口在 Selenium webdriver 中处理警报。警报可以分为三种类型——一个允许用户输入文本的提示、一个普通警报和一个确认警报。
默认情况下,webdriver 只可以访问主页面,一旦出现警报,就可以使用 switchTo().alert() 方法将焦点 webdriver 控制权切换到该警报。
普通警报如下图所示 −

确认警报如下图所示 −

提示警报如下图所示 −

要接受警报(点击警报中的确定按钮),使用 switchTo().alert().accept() 方法。要消除警报(点击警报中的取消按钮),使用 switchTo().alert().dismiss() 方法。
要提取警报文本,使用 switchTo().alert().getText() 方法。要在确认警报中输入文本,使用 switchTo().alert().sendKeys() 方法。
需要输入的文本作为参数传递给 sendKeys 方法。
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
public class AlertHandle{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
// identify element
WebElement c=driver.findElement(By.xpath("//button[text()='Click for JS Prompt']"));
c.click();
//shift to alert
Alert a = driver.switchTo().alert();
//get alert text
String s = a.getText();
System.out.println("Alert text is: " + s);
//input text to alert
a.sendKeys("Selenium");
//dismiss alert
a.dismiss();
c.click();
//accept alert
a.accept();
driver.quit();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP