Selenium定位策略(通過部分連結文字)

2019-10-16 23:03:43

在本節中,將學習如何使用部分連結文字的值定位特定Web元素。

考慮下面一個測試用例,它將自動化以下測試場景:

下面將逐步建立測試用例,以便完全了解如何使用定位器來識別和定位特定的Web元素。

第1步 - 啟動Eclipse IDE並開啟在本教學前幾節中建立的現有測試套件「Demo_Test」。

第2步 - 右鍵單擊「src」 檔案夾,然後從 New -> Class 建立一個新的類檔案。

將類的名稱命名為「Partial_Link」 ,然後單擊「完成」按鈕。

第3步 - 接下來開始編碼。

要呼叫Firefox瀏覽器,需要下載Gecko驅動程式並為Gecko驅動程式設定系統屬性。已在本教學前面的章節中討論過這個問題。 可以參考「在Firefox瀏覽器上執行測試」來了解如何下載和設定Firefox驅動程式的系統屬性。

以下是為Gecko驅動程式設定系統屬性的範例程式碼:

// System Property for Gecko Driver   
System.setProperty("webdriver.gecko.driver","D:\\\\GeckoDriver\\\\geckodriver.exe" );

之後使用 DesiredCapabilities 類初始化Gecko Driver。以下是使用DesiredCapabilities類初始化gecko驅動程式的範例程式碼。

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

結合上述兩個程式碼塊,將獲得啟動Firefox瀏覽器的程式碼片段。

  // System Property for Gecko Driver   
System.setProperty("webdriver.gecko.driver","D:\\\\GeckoDriver\\\\geckodriver.exe" );  

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

之後需要編寫程式碼來自動化第二個測試場景(導航到所需的URL),以下是導航到所需URL的範例程式碼:

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

到目前為止完整的程式碼如下所示:

import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.remote.DesiredCapabilities;  

public class Locator_One {  

    public static void main(String[] args) {  

    // System Property for Gecko Driver   
 System.setProperty("webdriver.gecko.driver","D:\\\\GeckoDriver\\\\geckodriver.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/testing.html");   

    }  

}

第4步 - 現在,將嘗試使用部分連結文字的值來定位所需的Web元素。 在Selenium中,查詢特定的Web元素涉及檢查其HTML程式碼。

檔案 - testing.html 頁面程式碼如下所示:

<html>
    <head>
        <title>Sample Test Page</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; ">
                    Sample WebPage for Automation Testing
                </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/">Link to Yiibai</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>

按照下面給出的步驟找到範例網頁上的連結文字。

它將啟動一個視窗,其中包含連結文字所涉及的所有特定程式碼。

選擇連結文字的值,即「Link to Yiibai」

使用部分連結文字定位Web元素的Java語法寫為:

driver.findElement(By.partialLinkText (<linktext>))

因此,要在範例網頁上找到連結文字,將要使用部分連結文字的值為:

driver.findElement(By.partialLinkText (<"Link to">))

同樣,要在在範例網頁上找到Submit 按鈕,將使用id屬性的值:

driver.findElement(By.id (<"idOfButton">))

第5步 -

要自動執行第3,第4和第5步的測試場景,還需要編寫程式碼,單擊連結文字。

下面是單擊部分連結文字的範例程式碼。

// Click on the Link Text using click() command  
 driver.findElement(By.partialLinkText("Link to")).click();

最終測試指令碼如下所示:

package com.yiibai;

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

public class Link_Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // System Property for Gecko Driver
        // System Property for Gecko Driver
        System.setProperty("webdriver.gecko.driver", "D:\\\\software\\\\WebDriver\\\\geckodriver.exe");
        System.setProperty("webdriver.firefox.bin", "D:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe");

        WebDriver driver = (WebDriver) new FirefoxDriver();

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

        // Click on the Link Text using click() command  
    driver.findElement(By.partialLinkText("Link to")).click();  
    }

}

第6步 - 右鍵單擊Eclipse程式碼,然後選擇:Run As -> Java Application

執行後,上述測試指令碼將啟動Firefox瀏覽器並自動執行所有測試方案。