Selenium WebDriver常用命令


前面,在IDE部分討論過Selenium命令是執行測試的Selenium中使用的一組命令。
下面給出了WebDriver中一些最常用的Selenium命令:

1. 獲取網頁

獲取網頁有兩種方法:

  • 使用Get方法 -
    driver.get("www.tw511.com");
    
  • 使用Navigate方法 -
    driver.navigate().to("https://www.tw511.com/selenium/");
    

2. 查詢表單並行送使用者輸入

driver.findElement(By.id("kw")).sendKeys("易-百教學");

3. 清除使用者輸入

clear()方法用於從文字框中清除使用者輸入。

driver.findElement(By.name("q")).clear();

4. 通過Web元素獲取資料

有時需要獲取通過web元素寫入的文字來執行某些斷言和偵錯。使用getText()方法來獲取通過任何web元素寫入的資料。

driver.findElement(By.id("element567")).getText();

5. 執行Click事件

click()方法用於對任何Web元素執行單擊操作。

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

6. 在瀏覽器歷史記錄中向後導航

driver.navigate().back();

7. 在瀏覽器歷史記錄中向前導航

driver.navigate().forward();

8. 重新整理/重新載入網頁

driver.navigate().refresh();

9. 關閉瀏覽器

driver.close();

10. 關閉瀏覽器和與驅動程式關聯的其他所有其他視窗

driver.quit();

11. 在Windows之間移動

driver.switchTo().window("windowName");

12. 在 frame 之間移動

driver.switchTo().frame("frameName");

13. 拖放

使用Action類執行拖放操作。

WebElement element = driver.findElement(By.name("source"));  
WebElement target = driver.findElement(By.name("target"));  

(new Actions(driver)).dragAndDrop(element, target).perform();

考慮一個範例測試指令碼,它將涵蓋大多數常用的WebDriver命令。

出於測試目的,在URL下使用虛擬網頁的程式碼(儲存到檔案:index.html):

<html>
    <head>
        <title>簡單測試頁面</title>
        <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <style></style>
    </head>
    <body style="font-family: cursive;">
        <div class="container">
            <div class="row">
                <div class="col-md-offset-2 col-md-8" style="font-size: 30; margin-top: 40px; ">
                    用於自動化測試的Web頁面範例
                </div>
            </div>

            <div class="row">
                <div class="col-md-12" style="font-size:20px; margin-top:40px;">
                    This is sample webpage with dummy elements that will help you in learning selenium automation.
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <b>This is sample text.</b>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p> <b>Link : </b><a href="https://www.tw511.com/">This is a link</a></p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><b>TextBox : </b><input id="fname" type="text" name="firstName" ></p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><b>Button : </b><button id="idOfButton" title="Click me!!" type="button" onclick="this.style.background='green';">Submit</button></p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><b>Radio button : </b> 
                        <form action="#">
                            <input id="male" type="radio" name="gender" value="male"> Male  
                            <input id="female" type="radio" name="gender" value="female"> Female
                        </form>
                    </p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><b>Checkbox :</b>
                        <form action="#">
                            <input type="checkbox" class="Automation" value="Automation"> Automation Testing
                            <input type="checkbox" class="Performance" value="Performance"> Performance Testing
                        </form>
                    </p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><b>Drop down :</b>
                        <select id="testingDropdown">
                            <option id="automation" value="Automation">Automation Testing</option>
                            <option id="performance" value="Performance">Performance Testing</option>
                            <option id="manual" value="Manual">Manual Testing</option>
                            <option id="database" value="Database">Database Testing</option>
                        </select>
                    </p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><button id="dblClkBtn" ondblclick="alert('hi, Yiibai Testing');">Double-click to generate alert box</button></p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p><b>Click button to generate Alert box : </b>
                          <button onclick="alert('hi, Yiibai Testing');">Generate Alert Box</button>
                    </p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p> <b> Click button to generate Confirm box : </b>
                        <button onclick="generateConfirmBox()">Generate Confirm Box</button>
                    </p>
                    <p id="demo"></p>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-12" style="font-size:15px;">
                    <p>Drag and drop example- drag the below image on the textbox</p>

                    <div id="targetDiv" ondrop="drop(event)" ondragover="allowDrop(event)" style="width:400px;height:150px;padding:10px;border:1px solid #aaaaaa;"></div>
                    <img id="sourceImage" src="https://www.tw511.com/static/img/logo.png" alt="yiibai" draggable="true" ondragstart="drag(event)" height="120px">

                </div>
            </div>
            <br>
        </div>
        <script>
            function generateConfirmBox()
            {
                var x;
                var r=confirm("Press a button!");
                if (r==true)
                {
                    x="You pressed OK!";
                }
                else
                {
                    x="You pressed Cancel!";
                }
                document.getElementById("demo").innerHTML=x;
            }

            function allowDrop(ev)
            {
                ev.preventDefault();
            }

            function drag(ev)
            {
                ev.dataTransfer.setData("Text",ev.target.id);
            }

            function drop(ev)
            {
                ev.preventDefault();
                var data=ev.dataTransfer.getData("Text");
                ev.target.appendChild(document.getElementById(data));
            }

        </script>
    </body>
</html>

網頁的預設介面如下所示 :

可以將此虛擬網頁用於Selenium測試實踐。
首先,需要自動化測試場景的瀏覽器,並下載瀏覽器驅動程式。已經在本教學的前幾節中討論了在不同瀏覽器上執行Selenium測試指令碼。
對於此測試,使用Firefox Gecko驅動程式在Firefox瀏覽器上自動化測試場景。

下面是帶有嵌入式註釋的範例測試指令碼。

import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.remote.DesiredCapabilities;  
import org.openqa.selenium.support.ui.Select;  

public class Second {  

    public static void main(String[] args) {  

          // System Property for Gecko Driver   
            // declaration and instantiation of objects/variables
        System.setProperty("webdriver.gecko.driver", "D:\\software\\WebDriver\\geckodriver.exe");
        System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe");


         // Initialize Gecko Driver using Desired Capabilities Class  
        DesiredCapabilities capabilities = DesiredCapabilities.firefox();  
        capabilities.setCapability("marionette",true);  
        WebDriver driver= new FirefoxDriver(capabilities);  

        // Launch Website  
     driver.navigate().to("http://localhost/index.html");  

        // Fetch the text "This is sample text." and print it on console  
        // Use the class name of the div to locate it and then fetch text using getText() method  
     String sampleText = driver.findElement(By.className("col-md-12")).getText();  
     System.out.println(sampleText);  

          // Use the linkText locator method to find the link and perform click using click() method  
     driver.findElement(By.linkText("This is a link")).click();  

          // Click on the textbox and send value  
     driver.findElement(By.id("fname")).sendKeys("JavaTpoint");  

        // Clear the text written in the textbox  
     driver.findElement(By.id("fname")).clear();  

        // Click on the Submit button using click() command  
     driver.findElement(By.id("idOfButton")).click();  

        // Locate the radio button by id and check it using click() function  
     driver.findElement(By.id("male")).click();  

        // Locate the checkbox by cssSelector and check it using click() function  
     driver.findElement(By.cssSelector("input.Automation")).click();  

        // Use Select class for selecting value from dropdown  
    Select dropdown = new Select(driver.findElement(By.id("testingDropdown")));  
    dropdown.selectByVisibleText("Automation Testing");  

        // Close the Browser  
             driver.close();  

    }  

}