selenium 訊息框元素定位處理
以下內容來自於“風少”的部落格 《元素定位:selenium訊息框處理 (alert、confirm、prompt)》
基礎普及
alert對話方塊 。細分三種,Alert,prompt,confirm
1. alert() 彈出個提示框 (確定)
警告訊息框 alert 方法有一個引數,即希望對使用者顯示的文字字串。該字串不是 HTML 格式。該訊息框提供了一個“確定”按鈕讓使用者關閉該訊息框,並且該訊息框是模式對話方塊,也就是說,使用者必須先關閉該訊息框然後才能繼續進行操作。
2. confirm() 彈出個確認框 (確定,取消)
確認訊息框 使用確認訊息框可向使用者問一個“是-或-否”問題,並且使用者可以選擇單擊“確定”按鈕或者單擊“取消”按鈕。confirm 方法的返回值為 true 或 false。該訊息框也是模式對話方塊:使用者必須在響應該對話方塊(單擊一個按鈕)將其關閉後,才能進行下一步操作。
3. prompt() 彈出個輸入框(確定,取消)
提示訊息框 提供了一個文字欄位,使用者可以在此欄位輸入一個答案來響應您的提示。該訊息框有一個“確定”按鈕和一個“取消”按鈕。如果您提供了一個輔助字串引數,則提示訊息框將在文字欄位顯示該輔助字串作為預設響應。否則,預設文字為 "<undefined>"。
selenium處理:
alert() 提示框
1. driver.switchTo().alert(); 獲取alert
2. alert.accept(); 點確定
3. alert.dismiss(); 點取消
4. alert.getText();獲取alert的內容
1. alert()
1 2 3 4 5 6 7 8 9 |
try
{
Alert alert =driver.switchTo().alert();
//使用driver.switchTo().alert()方法獲取到alert物件
Assert.assertEquals(
"彈框實際文字"
, alert.getText());
//斷言彈框文字是否和預期一致
alert.accept();
//點選確定
// alert.dismiss(); //點選取消
}
catch
(NoAlertPresentException exception){
//彈框未顯示,則跑出異常
Assert.fail(
"嘗試操作的alert框沒有被找到"
);
exception.printStackTrace();
}
|
2. confirm() ps:同alert一致
1 2 3 4 5 6 7 8 9 |
try
{
Alert alert =driver.switchTo().alert();
Assert.assertEquals(
"彈框實際文字"
, alert.getText());
alert.accept();
// alert.dismiss();
}
catch
(NoAlertPresentException exception){
Assert.fail(
"嘗試操作的alert框沒有被找到"
);
exception.printStackTrace();
}
|
3. prompt()
1 2 3 4 5 6 7 8 9 10 11 |
try
{
Alert alert =driver.switchTo().alert();
Assert.assertEquals(
"彈框實際文字"
, alert.getText());
alert.sendKeys(
"promt框中輸入的內容"
);
alert.accept();
// alert.dismiss();
}
catch
(NoAlertPresentException exception){
Assert.fail(
"嘗試操作的alert框沒有被找到"
);
exception.printStackTrace();
}
|