selenium webdriver處理alert、confirm、prompt

alert、confirm、prompt這樣的js對話框在selenium webdriveriver中處理十分方便簡潔。以下面html代碼爲例:

 

example.html

<html>

    <head>

        <title>Alert</title>

    </head>

    <body>

        <input id = "alert" value = "alert" type ="button" onclick = "alert('你好!請按確認繼續!');"/>

        <input id = "confirm" value= "confirm" type = "button" onclick = "confirm('確定?');"/>

        <inputid = "prompt" value = "prompt" type = "button"onclick = "var name = prompt('請輸入內容:','請輸入

 內容'); document.write(name) "/>

   </body>

 </html>


 以上html代碼在頁面上顯示了三個按鈕,點擊他們分別彈出alert、confirm、prompt對話框。如果在prompt對話框中輸入文字點擊確定之後,將會刷新頁面,顯示這些文字 。

 

selenium webdriveriver 處理這些彈層的代碼如下:

 

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriveriver;

import org.openqa.selenium.firefox.FirefoxDriveriver;

 

public class Alertpop{

 

        /**

         * @author tyf

         */

        publicstatic void main(String[] args) {

               //TODO Auto-generated method stub

                WebDriveriver driver = new FirefoxDriveriver();

               Stringurl = "file:///C:/selenium/Example.html";//Example.html文件所在的路徑

               driver.get(url);

              

               //點擊第一個按鈕,輸出對話框上面的文字

               driver.findElement(By.id("alert")).click();

               Alertalert = driver.switchTo().alert();

               Stringtext = alert.getText();

               System.out.println(text);

               alert.dismiss();//關閉alert

              

               //點擊第二個按鈕,輸出對話框上面的文字,然後確認

               driver.findElement(By.id("confirm")).click();

               Alertconfirm = driver.switchTo().alert();

               Stringtext1 = confirm.getText();

               System.out.println(text1);

               confirm.accept();

              

               //點擊第三個按鈕,輸入你的名字,然後點擊確認

               driver.findElement(By.id("prompt")).click();

               Alertprompt = driver.switchTo().alert();

               Stringtext2 = prompt.getText();

               System.out.println(text2);

               prompt.sendKeys("jarvi");

               prompt.accept();

              

        }

 

}

 

從以上代碼可以看出driver.switchTo().alert();這句可以得到alert\confirm\prompt對話框的對象,然後運用其方法對它進行操作。對話框操作的主要方法有:

 

  • getText()    得到文本內容
  • accept()      相當於點擊它的"確認"
  • dismiss()    相當於點擊"取消"對話框
  • sendKeys()  輸入值,這個alert\confirm沒有對話框就不能用了,不然會報錯。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章