如何使用Selenium命令點選警告視窗中的“確定”按鈕?
我們可以使用Selenium webdriver點選警告視窗中的“確定”按鈕。網頁上的警告視窗用於通知使用者或在警告視窗上執行某些操作。它是藉助Javascript設計的。
警告視窗可以分為三種類型——提示框、確認對話方塊或警告框。Selenium有多個API可以使用Alert介面來處理警告視窗。要點選警告視窗上的“確定”按鈕,首先我們必須使用switchTo().alert()方法切換到警告視窗。
接下來,要點選“確定”按鈕,我們必須使用accept()方法。請注意,我們無法透過檢查來識別警告視窗中的元素。此外,也沒有辦法為警告視窗建立自定義xpath。

讓我們使用一個帶有“確定”和“取消”按鈕的示例警告視窗進行操作。為了使用警告視窗,我們必須在程式碼中import 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://tutorialspoint.tw/selenium/selenium_automation_practice.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
driver.findElement(By.xpath("//button[@name='submit']")).click();
// Alert interface and switchTo().alert() method
Alert al = driver.switchTo().alert();
// click on OK to accept with accept()
al.accept();
driver.quit();
}
}
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP