Selenium高手必备:基于WebDriver的Web UI自动化

发表于:2021-12-22 08:56

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Paladin王    来源:51Testing软件测试网原创

  Selenium是当前最流行的Web UI自动化测试框架,熟悉Selenium的人也知道,Selenium是基于WebDriver。那么能不能不用Selenium,直接调用WebDriver来实现Web UI自动化呢?答案当然是可以的,本文就带你来实现基于WebDriver的Web U自动化。本文通过调用Selenium、Curl命令、直接调用ChromeDriver三种方式,实现了同样的功能。编程语言为C#,已在Visual Studio 2019测试通过,其他主流编程语言也可以完成同样功能。对比三种实现方式,大家就可以容易的理解如何不用Selenium而直接调用WebDriver完成Web U自动化。阅读以下内容前,需要有Selenium和WebDriver相关基础知识。

  手动步骤
  1.打开Chrome浏览器
  2.进入https://www.baidu.com/主页
  3.搜索框输入“Selenium”
  4.点击“百度一下”
  5.关闭Chrome浏览器

  调用Selenium的C#代码
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace HelloSelenium
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = null;
            try
            {
                //1.  打开Chrome浏览器
                driver = new ChromeDriver();
                //2.  进入https://www.baidu.com/主页
                driver.Navigate().GoToUrl("https://www.baidu.com/");
                //3.    搜索框输入“Selenium”
                driver.FindElement(By.Id("kw")).SendKeys("Selenium");
                //4.  点击“百度一下”
                driver.FindElement(By.Id("su")).Click();
            }
            finally
            {
                //5.  关闭Chrome浏览器
                if (driver != null)
                {
                    driver.Dispose();
                }
            }
        }
}
}

  Curl命令
  1.打开Chrome浏览器
  启动命令提示符,执行chromedriver.exe --port=9515 (注意选用与Chrome版本对应的chromedriver版本,端口只要未被占用即可)。

  另起一个命令提示符,执行curl命令(注意端口号),记住返回的sessionId。
curl  -d @JsonFile1.json http://localhost:9515/session

  JsonFile1.json内容:
  {
    "desiredCapabilities": {
      "caps": {
        "nativeEvents": false,
        "browserName": "chrome",
        "version": "",
        "platform": "ANY"
      }
    }
  }

  2.进入https://www.baidu.com/主页
curl -d @JsonFile2.json http://localhost:9515/session/36d903cbd2177c278b5d39bbe74a3318/url

  JsonFile2.json内容:
  {"url":"https://www.baidu.com/"}

  3.搜索框输入“Selenium”
  获取elementId:
curl -d @JsonFile3.json http://localhost:9515/session/36d903cbd2177c278b5d39bbe74a3318/element

  JsonFile3.json内容:{"using":"css selector","value":"#kw"}

  输入“Selenium”:
curl -d @JsonFile4.json http://localhost:9515/session/36d903cbd2177c278b5d39bbe74a3318/element/0.7861531328870939-1/value

  JsonFile4.json内容:{"value":["Selenium"]}

  4.点击“百度一下”
  获取elementId:
curl -d @JsonFile5.json http://localhost:9515/session/36d903cbd2177c278b5d39bbe74a3318/element

  JsonFile5.json内容:
  {"using":"css selector","value":"#su"}

  点击:
curl -d @JsonFile4.json curl -d @JsonFile6.json http://localhost:9515/session/36d903cbd2177c278b5d39bbe74a3318/element/0.7861531328870939-2/click

  JsonFile6.json内容:
  {}

  5.关闭Chrome浏览器
  关闭Chrome:
关闭Chrome
curl -X DELETE http://localhost:9515/session/36d903cbd2177c278b5d39bbe74a3318

  关闭chromedriver.exe:
curl http://localhost:9515/shutdown

  调用ChromeDriver的C#代码
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HelloSelenium
{
    class Program
    {
        static IList<HttpCmd> cmdArr;

        static readonly string baseUrl = "http://localhost:9515/";

        static readonly string extendUrlFormat1 = "session";
        static readonly string extendUrlFormat2 = "session/{sessionId}/url";
        static readonly string extendUrlFormat3 = "session/{sessionId}/element";
        static readonly string extendUrlFormat4 = "session/{sessionId}/element/{elementId}/value";
        static readonly string extendUrlFormat5 = "session/{sessionId}/element";
        static readonly string extendUrlFormat6 = "session/{sessionId}/element/{elementId}/click";
        static readonly string extendUrlFormat7 = "session/{sessionId}";
        static readonly string extendUrlFormat8 = "shutdown";

        static readonly string jsonData1 = @"{""desiredCapabilities"": { ""caps"": {""nativeEvents"": false, ""browserName"": ""chrome"", ""version"": """",""platform"": ""ANY""}}}";
        static readonly string jsonData2 = @"{""url"":""https://www.baidu.com/""}";
        static readonly string jsonData3 = @"{""using"":""css selector"",""value"":""#kw""}";
        static readonly string jsonData4 = @"{""value"":[""Selenium""]}";
        static readonly string jsonData5 = @"{""using"":""css selector"",""value"":""#su""}";
        static readonly string jsonData6 = @"{}";

        static Dictionary<string, string> dicSe = new Dictionary<string, string>()
            {{"{sessionId}", null}};
        static Dictionary<string, string> dicSeEl = new Dictionary<string, string>()
            {{"{sessionId}", null},{"{elementId}", null}};

        static Program()
        {
            cmdArr = new List<HttpCmd>()
            {
                new HttpCmd(null, null, null, null),
                new HttpCmd("POST", extendUrlFormat1, jsonData1, null),
                new HttpCmd("POST", extendUrlFormat2, jsonData2, dicSe),
                new HttpCmd("POST", extendUrlFormat3, jsonData3, dicSe),
                new HttpCmd("POST", extendUrlFormat4, jsonData4, dicSeEl),
                new HttpCmd("POST", extendUrlFormat5, jsonData5, dicSe),
                new HttpCmd("POST", extendUrlFormat6, jsonData6, dicSeEl),
                new HttpCmd("DELETE", extendUrlFormat7, null, dicSe),
                new HttpCmd("GET", extendUrlFormat8, null, null),
            };
        }
        

        static void Main(string[] args)
        {
            Process p = null;
            try
            {
                string response = null, sessionId = null, elementId = null, extendUrl;
                JObject jObj = null;

                //1.  打开Chrome浏览器
                //启动chromedriver.exe
                p = Process.Start(@"D:\Software\chromedriver.exe", "--port=9515");
                Thread.Sleep(1000);

                //启动chrome
                response = HttpOp(cmdArr[1]);
                jObj = JsonConvert.DeserializeObject(response) as JObject;
                sessionId = jObj["sessionId"].Value<string>();
                dicSe["{sessionId}"] = sessionId;
                dicSeEl["{sessionId}"] = sessionId;
                Thread.Sleep(1000);

                //2.  进入https://www.baidu.com/主页
                HttpOp(cmdArr[2]);
                Thread.Sleep(1000);

                //3.    搜索框输入“Selenium”
                //获取elementId
                response = HttpOp(cmdArr[3]);
                jObj = JsonConvert.DeserializeObject(response) as JObject;
                elementId = jObj["value"]["ELEMENT"].Value<string>();
                dicSeEl["{elementId}"] = elementId;
                //输入“Selenium”
                HttpOp(cmdArr[4]);
                Thread.Sleep(1000);

                //4.  点击“百度一下”
                //获取elementId
                response = HttpOp(cmdArr[5]);
                jObj = JsonConvert.DeserializeObject(response) as JObject;
                elementId = jObj["value"]["ELEMENT"].Value<string>();
                dicSeEl["{elementId}"] = elementId;
                //点击
                HttpOp(cmdArr[6]);
                Thread.Sleep(1000);

                //5.  关闭Chrome浏览器
                //关闭Chrome
                HttpOp(cmdArr[7]);
                //关闭chromedriver
                HttpOp(cmdArr[8]);
            }
            finally
            {
                if (p != null)
                {
                    p.WaitForExit(3000);
                    p.Dispose();
                }
            }
        }

        private static string HttpOp(HttpCmd cmd)
        {
            var fullUrl = baseUrl + cmd.ExtendUrl;
            HttpClient client = new HttpClient();
            Task<HttpResponseMessage> response = null;
            switch (cmd.Method)
            {
                case "GET":
                    response = client.GetAsync(fullUrl);
                    break;
                case "DELETE":
                    response = client.DeleteAsync(fullUrl);
                    break;
                case "POST":
                    HttpContent content = new StringContent(cmd.JsonData, Encoding.UTF8, "application/json");
                    response = client.PostAsync(fullUrl, content);
                    break;
            }
            return response.Result.Content.ReadAsStringAsync().Result;
        }

        internal class HttpCmd
        {
            public string Method { get; set; }
            public string ExtendUrlFormat { get; set; }
            public string JsonData { get; set; }
            public Dictionary<string, string> ParaDictionary { get; set; }

            public string ExtendUrl => BuildExtendUrl();

            public HttpCmd(string method, string extendUrlFormat, string jsonData, Dictionary<string, string> paraDictionary)
            {
                this.Method = method;
                this.ExtendUrlFormat = extendUrlFormat;
                this.JsonData = jsonData;
                this.ParaDictionary = paraDictionary;
            }

            private string BuildExtendUrl()
            {
                var extendUrl = ExtendUrlFormat;
                if (ParaDictionary != null && ParaDictionary.Count > 0)
                {
                    foreach (var pair in ParaDictionary)
                    {
                        extendUrl = extendUrl.Replace(pair.Key, pair.Value);
                    }
                }

                return extendUrl;
            }
        }
    }
}

  总结
  Curl命令就是Http调用WebDriver命令。
  调用ChromeDriver的代码也是Http调用WebDriver命令。
  调用Selenium的代码实际上还是Http调用WebDriver命令。只不过不是直接调用,而是通过Selenium去执行WebDriver命令。Selenium封装了WebDriver。至于Selenium具体是怎么封装WebDriver的,内容较多,本文不做这部分的分析。
  使用直接Http调用WebDriver命令的方式来做Web UI自动化,写代码很麻烦,实用价值很低。本文并不鼓励大家在实际工作中使用这样的方式来做自动化。但是,如果你在工作中经常用到Selenium,想具体了解Selenium的原理,成为高手,学习这种方式是必要的。这种方式非常有助于深入学习和理解Selenium,是Selenium高手所必备的知识和技能。

  版权声明:本文出自51Testing会员投稿,51Testing软件测试网及相关内容提供者拥有内容的全部版权,未经明确的书面许可,任何人或单位不得对本网站内容复制、转载或进行镜像,否则将追究法律责任。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号