当前位置: 首页 > 教程 > Selenium >

Selenium WebDriver常用命令

精华
小牛编辑
161浏览
2023-03-14

前面,在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.xnip.cn/">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.xnip.cn/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();  

    }  

}