Selenium系列之--07 操做遠程瀏覽器

Selenium遠程控制瀏覽,能夠經過以下兩種方式實現,本質上都是Selenium Gridhtml

a.  客戶機啓Selenium Standalone Server 做爲遠程服務,服務端經過調用RemoteWebDriver類來實現調用客戶機瀏覽器;java

b.  經過部署Selenium Grid 實現分佈式執行UI自動化測試;node

1、環境準備

1. 安裝JDK(jdk1.8.0_101);
2. 下載安裝firefox,chrome瀏覽器 ;
3. 下載selenium-server-standalone.jar (官方下載地址);
4. 下載InternetExplorerDriver,ChromeDriver,geckodriver(selenium3.0以及以後的版本支持的firefox driver)git

2、RemoteWebDriver

Selenium框架的遠程控制主要是經過RemoteWebDriver這個類來實現的。github

本例中【測試代碼放在服務器上,執行代碼的機器爲客戶機】web

客戶機操做chrome

2.1. 首先配置JDK,並配置環境變量,增長放WebDriver文件的地址(即將相應的WebDriver文件夾配置到環境變量的path中)json

2.2. 啓動獨立測試jar包(注意JAR包的版本號)api

java -jar E:\Selenium\selenium-server-standalone-2.46.0.jar

服務端操做瀏覽器

2.3. 驗證客戶端響應是否正常。在瀏覽器中輸入地址:http://客戶機IP地址:4444/wd/hub/ ,顯示以下頁面。

2.4. 寫測試代碼,經過RemoteWebDriver調用客戶機

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class RemoteIEBrowser {
    public static void main(String[] args) throws MalformedURLException, InterruptedException {
        // RemoteWebDriver的基本使用

        //第一個參數:表示服務器的地址。第二個參數:表示預期的執行對象,其餘的瀏覽器均可以以此類推
        WebDriver driver = new RemoteWebDriver(new URL("http://10.10.12.162:4444/wd/hub/"), DesiredCapabilities.internetExplorer());
        driver.manage().window().maximize();
        driver.get("http://www.baidu.com");
        Thread.sleep(2000);
        JavascriptExecutor js = (JavascriptExecutor)driver;
        js.executeScript("alert('我如今在服務器')");
        Thread.sleep(2000);
        driver.quit();
   }
}

2.5. 執行腳本。執行過程當中能夠看到客戶端的瀏覽器被調用,同時cmd窗口中打印出相關的運行信息,以下 

3、Selenium GRID

Selenium Grid 用於解決分佈式執行UI測試的痛點,Selenium2以後Selenium Grid被集成到了 Selenium Server 中,即包含在 selenium-server-standalone-x-x-x.jar 包中,其結構圖以下所示:

 

Selenium Grid實際它是基於Selenium RC的,而所謂的分佈式結構就是由一個hub節點和若干個node代理節點組成。Hub用來管理各個代理節點的註冊信息和狀態信息,而且接受遠程客戶端代碼的請求調用,而後把請求的命令轉發給代理節點來執行。

  • 3.1. 啓動HUB,腳本以下,

java -jar selenium-server-standalone-2.46.0.jar -role hub -maxSession 10 -port 4444
 
-role hub :啓動的是HUB,
-maxSession :最大會話數量
-prot:指定端口

  • 3.2. 測試HUB是否啓動成功

驗證hub是否正常啓動正常。在瀏覽器中輸入地址:http://客戶機IP地址:4444/grid/console/ ,顯示以下頁面。

  • 3.3. 啓動NODE節點
java -Dwebdriver.IE.driver=E:\Selenium\IEDriverServer.exe -jar E:\Selenium\selenium-server-standalone-2.46.0.jar -role node -port 6666 -hub http://10.10.12.161:4444/grid/register -browser browserName=IE

-role node :啓動的是node節點 -hub :hub 的地址及端口號 -Dwebdriver.chrome.driver:驅動類型 -maxSession :最大會話數量 -browserName:瀏覽器名稱 -注意,有些參數若是沒必要要時,是能夠不用寫的,好比platform是系統.
  • 3.4. hub端瀏覽器刷新頁面http://localhost:4444/grid/console,這裏也能夠看見node節點的狀況.

  • 3.5. 調用NODE也是經過RemoteWebDriver對象. 代碼同2.4
// 封裝方法以下:

public static WebDriver getRemoteIEDriver(String myUrl) { try { DesiredCapabilities capabilities = DesiredCapabilities .internetExplorer(); URL urlInstance = new URL(myUrl); // 指定URL WebDriver driver = new RemoteWebDriver(urlInstance, capabilities); // 使用RemoteWebDriver初始化 logger.info("遠程瀏覽器啓動完成!"); return driver; } catch (Exception e) { logger.error("遠程瀏覽器啓動失敗!"); logger.error("===============>" + e.getMessage().toString()); e.printStackTrace(); return null; } }

測試類以下:

public class RemoteIEBrowser {

    public static void main(String[] args) throws MalformedURLException, InterruptedException {
        // RemoteWebDriver的基本使用

        //第一個參數:表示服務器的地址。第二個參數:表示預期的執行對象,其餘的瀏覽器均可以以此類推
        WebDriver driver = getRemoteIEDriver("http://10.10.12.162:6666/wd/hub/");

        // WebDriver driver = getRemoteIEDriver("http://10.10.12.161:4444/wd/hub/");
        driver.manage().window().maximize();
        driver.get("http://www.baidu.com");
        Thread.sleep(2000);
        JavascriptExecutor js = (JavascriptExecutor)driver;
        js.executeScript("alert('我如今在服務器')");
        Thread.sleep(2000);
        driver.quit();
   }

}

 注意此時能夠經過調用hub節點,由hub自動實現分發,也能夠直接調用某個node節點

衍生問題

問題1. 直接調用hub分發任務時,怎麼查看分發實際上運行在那臺服務上(IP)

代碼以下

public static String getRemoteIp(String hub, int port, WebDriver driver) {
        String node = "";
        try {
            HttpHost host = new HttpHost(hub, port);
            DefaultHttpClient client = new DefaultHttpClient();
            URL session = new URL("http://" + hub + ":" + port
                    + "/grid/api/testsession?session="
                    + ((RemoteWebDriver) driver).getSessionId());
            BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest(
                    "POST", session.toExternalForm());
            HttpResponse response = client.execute(host, req);
            Map<String, Object> map = new HashMap<String, Object>();
            map = new Gson().fromJson(
                    EntityUtils.toString(response.getEntity()), map.getClass());
            String proxyId = (String) map.get("proxyId");
            node = (proxyId.split("//")[1].split(":")[0]);
            logger.info("WebDriver running in node:" + node);
        } catch (Exception ex) {
            logger.error("===============>" + ex.getMessage().toString());
            ex.printStackTrace();
        }
        return node;
    }

 參考資料

問題2 Selenium grid configuration using JSON File:

SELENIUM 3.0 OR ABOVE

SELENIUM 2.0 

----hub
java -jar selenium-server-standalone-2.46.0.jar -role hub -hubConfig hubconfig.json


----node
Java -Dwebdriver.chrome.driver="chromedriver.exe" -Dwebdriver.ie.driver="IEDriverServer.exe" -Dwebdriver.gecko.driver="geckodriver.exe" -jar selenium-server-standalone-2.46.0.jar -role node -nodeConfig grid-node.json

 

-throwOnCapabilityNotPresent: [true|false]
默認爲true,若是爲true則hub只有在當前有測試代理註冊的狀況下才會接受測試請求;若是爲false則若是當前沒有代理註冊也會接受請求保存到隊列直到有代理註冊爲止。

-capabilityMatcher:xxx
一個實現了CapabilityMatcher接口的類,默認指向org.openqa.grid.internal.utils.DefaultCapabilityMatcher;該類用於實現grid在分佈測試任務到對應代理時所使用的匹配規則,若是想要更精確的測試分配規則,那麼就註冊一個本身定義的匹配類。

-prioritizer:XXXclass
一個實現了Prioritizer接口的類。設置grid執行test任務的優先邏輯;默認爲null,先來先執行。

-newSessionWaitTimeout:XXX
默認-1,即沒有超時;指定一個新的測試session等待執行的間隔時間。即一個代理節點上先後2個測試中間的延時時間,單位爲毫秒。

-servlets: XXXserlet
在hub上註冊一個新的serlet,訪問地址爲/grid/admin/XXXserlet

-browserTimeout:
瀏覽器無響應的超時時間

-role: [node|wd|rc]
爲node值時表示註冊的RC能夠支持selenium一、selenium2兩種方式的測試請求,推薦;
爲wd值時表示註冊的RC僅支持selenium2的webdriver方式的測試請求,遺留;
爲rc值時表示註冊的RC僅支持selenium1方式的測試請求,遺留。

-hub:url_to_hub
url_to_hub值爲hub啓動的註冊地址,默認爲ttp://ip_for_hub:4444/grid/register;具體的根據你啓動hub時的參數所對應。
該選項包含了-hubHost和-hubPort兩個選項

-registerCycle:xxx
代理節點自動從新註冊的週期,單位毫秒;適應於重啓了hub時不須要重啓全部的代理節點。

-nodePolling:XXX
hub檢查代理節點的週期

-unregisterIfStillDownAfter:XXX
單位毫秒,設定代理節點在無響應多長時間後hub纔會註銷代理節點註冊信息;默認1分鐘

-nodeTimeout:xxx
客戶端的無意跳超時時間

-maxSession:xx
一個代理節點能夠同時啓動的瀏覽器最大數量,即session數量

-cleanupCycle:XXX
代理節點檢查超時的週期

 

Summary(轉)

  • Selenium Grid is used to run multiple tests simultaneously on different browsers and platforms.
  • Grid uses the hub-node concept.
  • The hub is the central point wherein you load your tests.
  • Nodes are the Selenium instances that will execute the tests that you loaded on the hub.
  • To install Selenium Grid, you only need to download the Selenium Server jar file - the same file used in running Selenium RC tests.
  • There are 2 ways to verify if the hub is running: one was through the command prompt, and the other was through a browser
  • To run test scripts on the Grid, you should use the DesiredCapabilities and the RemoteWebDriver objects.
  • DesiredCapabilites is used to set the type of browser and OS that we will automate
  • RemoteWebDriver is used to set which node (or machine) that our test will run agains

Original URL: https://www.guru99.com/introduction-to-selenium-grid.html

相關文章
相關標籤/搜索