JS弹框出现在页面主要分为3种,第一种是Alert警告弹框,该弹窗只有一个确认按钮;第二种是Confirm确认框,该弹窗有确认和取消按钮;第三种是Prompt确认框,该弹窗可以输入内容。selenium处理JS弹框主要用到了org.openqa.selenium.Alert
包,核心操作步骤就是要先切换到弹窗:Alert alert=driver.switchTo().Alert()
。其中常用的方法有:accept()接收警告信息或点击确认按钮;dismiss()忽略警告信息或点击取消按钮;getText()获取弹框中的文字信息;sengKeys()在弹框中输入信息等。
1、Alert警告弹框,selenium+Java具体示例代码参考如下:
public class Alert_js {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Webdriver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.runoob.com/try/try.php?filename=tryjs_alert");
driver.manage().window().maximize();
//切换到iframe
driver.switchTo().frame("iframeResult");
//点击弹出弹窗
driver.findElement(By.xpath("//input[@type='button']")).click();
Thread.sleep(2000);
//切换到Alert弹窗
Alert alert=driver.switchTo().alert();
//点击确定按钮
alert.accept();
Thread.sleep(2000);
//关闭浏览器
driver.quit();
}
}
2、Confirm确认框,selenium+Java具体示例代码参考如下:
public class Confirm_js {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Webdriver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.runoob.com/try/try.php?filename=tryjs_confirm");
//切换iframe
driver.switchTo().frame("iframeResult");
//点击弹出Confirm确认框
driver.findElement(By.xpath("//button[text()='点我']")).click();
Thread.sleep(1000);
//切换到Confirm确认框
Alert alert=driver.switchTo().alert();
Thread.sleep(1000);
//点击确认框内的取消按钮
alert.dismiss();
Thread.sleep(1000);
//关闭浏览器
driver.quit();
}
}
3、Prompt确认框,selenium+Java具体示例代码参考如下:
public class Prompt_js {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Webdriver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.runoob.com/try/try.php?filename=tryjs_prompt");
//切换iframe
driver.switchTo().frame("iframeResult");
//点击弹出Prompt确认框
driver.findElement(By.xpath("//button[text()='点我']")).click();
Thread.sleep(1000);
//切换到Prompt确认框
Alert alert=driver.switchTo().alert();
//在弹窗中输入文字
alert.sendKeys("一个测试弹窗");
Thread.sleep(1000);
//点击确认按钮
alert.accept();
Thread.sleep(1000);
//关闭浏览器
driver.quit();
}
}