「text」はダイアログに表示された文字列を取得します。
言い換えれば、取得できるのはダイアログ上に表示された文字列のみで、ダイアログ以外の箇所で文字列の取得はできません。
「text」は、「accept():OKボタン押下」、「dismiss():Cancelボタン押下」などと同様にダイアログを制御するAlertクラスのメンバです。
説明
サンプル
from selenium import webdriver from selenium.webdriver.chrome import service from selenium.webdriver.common.alert import Alert #ChromeDriverのパスを変数に設定 CHROMEDRIVER = "D:\driver\chromedriver.exe" #ChromeDriverのstartとstopを制御するServiceオブジェクトを介してパスを渡す chrome_service = service.Service(executable_path=CHROMEDRIVER) #Chromeを起動 driver = webdriver.Chrome(service=chrome_service) #指定したURLに遷移する<図1> driver.get("file://D:/AutoTest/Alert_getText.html") #表示されたダイアログの文字列を取得する alertText = Alert(driver).text #取得した文字列を表示する print(alertText)
※selenium version 4.1.3で動作確認をしています
実行結果
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にすると解説のテロップが表示されます※