Selenium WebDriver常用命令

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

1. 獲取網頁

獲取網頁有兩種方法:

  • 使用Get方法 -

    driver.get("www.yiibai.com");
  • 使用Navigate方法 -

    driver.navigate().to("https://yiibai.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.yiibai.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.yiibai.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 WebDriver常用命令

可以將此虛擬網頁用於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();  

    }  

}