「getText」はダイアログに表示された文字列を取得します。
言い換えれば、取得できるのはダイアログ上に表示された文字列のみで、ダイアログ以外の箇所で文字列の取得はできません。
「getText」は、「accept():OKボタン押下」、「dismiss():Cancelボタン押下」などと同様にダイアログを制御するAlertインターフェースのメンバです。
説明
◆メソッド ・java.lang.String getText() ◆使用形態 ・alert.getText() ◆備考 ・driver.switchTo().alert()でアクティブなダイアログを指定 ◆関連項目 ・スクリーンショット(ファイル)を取得する ・タイトルを取得する
サンプル
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebTest{
public static void main(String[] args){
//Chrome制御のためChromeDriverのパスを指定
System.setProperty("webdriver.chrome.driver",
"D:\\AutoTest\\chromedriver.exe");
//Chromeを起動する
WebDriver driver = new ChromeDriver();
//指定したURLに遷移する<図1>
driver.get("file://D:/AutoTest/Alert_getText.html");
//画面表示されたダイアログをアクティブにする
Alert alert = driver.switchTo().alert();
//ダイアログに表示された文字列を取得する
System.out.println(alert.getText());
}
}※selenium version 4.1.4で動作確認をしています
実行結果
Start!
Alert_getText.html<図1>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Alert</title>
</head>
<body>
<script>
alert("Start!");
</script>
</body>
</html>
動画デモ
※字幕をONにすると解説のテロップが表示されます※
