• WebDriver介绍


    什么是Selenium 和WebDriver?

    Selenium是一个浏览器自动化操作框架。Selenium主要由三种工具组成。第一个工具SeleniumIDE,是Firefox的扩展插件,支持用户录制和回访测试。录制/回访模式存在局限性,对许多用户来说并不适合,因此第二个工具——Selenium WebDriver提供了各种语言环境的API来支持更多控制权和编写符合标准软件开发实践的应用程序。最后一个工具——SeleniumGrid帮助工程师使用Selenium API控制分布在一系列机器上的浏览器实例,支持并发运行更多测试。在项目内部,它们分别被称为“IDE”、“WebDriver”和“Grid”。 

    这里主要介绍它的第二个工具:WebDriver。

    官网上是这么介绍它的:WebDriver is a clean, fast framework for automated testing of webapps. 但是我觉得它并不局限与进行自动化测试,完全可以用作其它用途。

    WebDriver针对各个浏览器而开发,取代了嵌入到被测Web应用中的JavaScript。与浏览器的紧密集成支持创建更高级的测试,避免了JavaScript安全模型导致的限制。除了来自浏览器厂商的支持,WebDriver还利用操作系统级的调用模拟用户输入。WebDriver支持Firefox(FirefoxDriver)、IE (InternetExplorerDriver)、Opera (OperaDriver)和Chrome (ChromeDriver)。 它还支持Android (AndroidDriver)和iPhone (IPhoneDriver)的移动应用测试。它还包括一个基于HtmlUnit的无界面实现,称为HtmlUnitDriver。WebDriver API可以通过Python、Ruby、Java和C#访问,支持开发人员使用他们偏爱的编程语言来创建测试。

    如何使用?(相关教程:http://www.51testing.com/zhuanti/webdriver.htm)

    首先,你需要将WebDriver的JAR包加入到你项目中CLASSPATH中。你可以Download它通过http://code.google.com/p/selenium/downloads/list

    如果你使用的是maven构建你的项目,只需要在pom.xml文件中加入下面的依赖项即可。

            <dependency>

               <groupId>org.seleniumhq.selenium</groupId>

               <artifactId>selenium-java</artifactId>

                <version>2.25.0</version>

            </dependency>

            <dependency>

               <groupId>org.seleniumhq.selenium</groupId>

               <artifactId>selenium-server</artifactId>

               <version>2.25.0</version>

            </dependency>

    然后,你就可以使用它了。WebDriver的API遵从”Best Fit”原则,在保持良好的用户体验性和灵活性之间找到一个最佳的平衡点。

    下面的例子是使用HtmlUnitDriver。HtmlUnitDriver只会在内存中执行这段代码,不会弹出一个真实的页面。

    packageorg.openqa.selenium.example;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.htmlunit.HtmlUnitDriver;

    public class Example  {
        public static void main(String[] args) {
            // Create a new instance of the html unit driver
            // Notice that the remainder of the code relies onthe interface, 
            // not the implementation.
            WebDriver driver = new HtmlUnitDriver();

            // And now use this to visit Google
            driver.get("http://www.google.com");

            // Find the text input element by its name
            WebElement element = driver.findElement(By.name("q"));

            // Enter something to search for
            element.sendKeys("Cheese!");

            // Now submit the form. WebDriver will find theform for us from the element
            element.submit();

            // Check the title of the page
            System.out.println("Page title is: " +driver.getTitle());
        }
    }

    如果你想使用Firefox浏览器。你只需要将WebDriver driver = new FirefoxDriver()。前提是你的Firefox被安装在默认的位置。

    操作系统

    Firefox默认安装位置

    Linux

    firefox (found using "which")

    Mac

    /Applications/Firefox.app/Contents/MacOS/firefox

    Windows

    %PROGRAMFILES%\Mozilla Firefox\firefox.exe

    如果你的FireFox没有被安装在指定的位置,你可以设置“webdriver.firefox.bin”

    环境变量的值来指定它的位置。在Java中可以使用如下代码:

    System.setProperty("webdriver.firefox.bin","thelocation of Firefox");

    如果要使用Chrome浏览器的话相对麻烦些。你需要首先下载一个ChromeDriver(下载地址:http://code.google.com/p/chromedriver/downloads/list)。这个程序是由Chrome团队提供的,你可以看做它是链接WebDriver和Chrome浏览器的桥梁。然后启动ChromeDriver,你会得到一个Url及监听端口。然后使用webDriver = newRemoteWebDriver(url, DesiredCapabilities.chrome())创建一个ChromeWebDriver进行操作。当然你可以在一个子线程中启动ChromeDriver,并设置给WebDriver。

            File file = new File(your chromedriverfile path);

       ChromeDriverService service = newChromeDriverService.Builder().usingChromeDriverExecutable(file).usingAnyFreePort().build();

            service.start();

    WebDriver  webDriver = new ChromeDriver(service);

    …..

    …..

    ….

      service.stop();

    WebDriver如何工作

    WebDriver是W3C的一个标准,由Selenium主持。

    具体的协议标准可以从http://code.google.com/p/selenium/wiki/JsonWireProtocol#Command_Reference   查看。

    从这个协议中我们可以看到,WebDriver之所以能够实现与浏览器进行交互,是因为浏览器实现了这些协议。这个协议是使用JOSN通过HTTP进行传输。

    它的实现使用了经典的Client-Server模式。客户端发送一个requset,服务器端返回一个response。

    我们明确几个概念。

    Client

    调用 WebDriverAPI的机器。

    Server

    运行浏览器的机器。Firefox浏览器直接实现了WebDriver的通讯协议,而Chrome和IE则是通过ChromeDriver和InternetExplorerDriver实现的。

    Session

    服务器端需要维护浏览器的Session,从客户端发过来的请求头中包含了Session信息,服务器端将会执行对应的浏览器页面。

    WebElement

    这是WebDriverAPI中的对象,代表页面上的一个DOM元素。

    举个实际的例子,下面代码的作用是”命令”firefox转跳到google主页:

           WebDriver driver = new FirefoxDriver();
            //实例化一个Driver
     
            driver.get("http://www.google.com");

    在执行driver.get("http://www.google.com")这句代码时,client,也就是我们的测试代码向remote server发送了如下的请求:

    POSTsession/285b12e4-2b8a-4fe6-90e1-c35cba245956/url  post_data{"url":"http://google.com"}  

    通过post的方式请求localhost:port/hub/session/session_id/url地址,请求浏览器完成跳转url的操作。

    如果上述请求是可接受的,或者说remote server是实现了这个接口,那么remote server会跳转到该post data包含的url,并返回如下的response

    {"name":"get","sessionId":"285b12e4-2b8a-4fe6-90e1-c35cba245956","status":0,"value":""} 

    该response中包含如下信息

    name:remote server端的实现的方法的名称,这里是get,表示跳转到指定url;

    sessionId:当前session的id;

    status:请求执行的状态码,非0表示未正确执行,这里是0,表示一切ok不许担心;

    value:请求的返回值,这里返回值为空,如果client调用title接口,则该值应该是当前页面的title;

    如果client发送的请求是定位某个特定的页面元素,则response的返回值可能是这样的:

    {"name":"findElement","sessionId":"285b12e4-2b8a-4fe6-90e1-c35cba245956","status":0,"value":{"ELEMENT":"{2192893e-f260-44c4-bdf6-7aad3c919739}"}} 

    name,sessionId,status跟上面的例子是差不多的,区别是该请求的返回值是ELEMENT:{2192893e-f260-44c4-bdf6-7aad3c919739},表示定位到元素的id,通过该id,client可以发送如click之类的请求与 server端进行交互。

    如何用webdriver打开一个浏览器,我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器,很多新的特性都会在firefox中体现。但是做页面的测试,启动速度比较慢,启动以后运行速度还是可以接受的。

    启动firefox浏览器

    新建一个firefoxDriver
    如果火狐浏览器没有默认安装在C盘,需要制定其路径

    System.setProperty("webdriver.firefox.bin", "D:/Program Files/Mozilla firefox/firefox.exe"); 
    
    WebDriver driver = newFirefoxDriver(); 
    
    

    启动IE浏览器

    //Create a newinstance of the Internet Explorer driver
    WebDriver driver = newInternetExplorerDriver ();

    启动HtmlUnit浏览器

    //Createa new instance of the HtmlUnit driver
    WebDriverdriver = new HtmlUnitDriver();

    启动Chrome浏览器

              下载ChromeDriver.exe请点 这里

    //Createa new instance of the Chromedriver

    System.setProperty(“webdriver.chrome.driver”, bsPath);
    WebDriverdriver = new ChromeDriver();

    对web页面进行测试,首先要打开被测试页面的地址(如:http://www.baidu.com),web driver 提供的get方法可以打开一个页面:
    // And now use thedriver to visit Google
    driver.get(“http://www.baidu.com“);
    //也可以调用以下方法
    driver.navigate().to(“http://www.baidu.com“);
    测试脚本如下
    package com.test.ui.demo;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;

    public class TestWebDriver {undefined
    private WebDriver driver = null;
    private String url = “http://www.baidu.com“;
    //每个用例执行前会执行该方法
    @BeforeMethod
    public void startUp(){undefined
    //如果firefox没有安装在c盘需要执行下面这句,否则请注释掉
    System.setProperty(“webdriver.firefox.bin”, “D:/Program Files/Mozilla firefox/firefox.exe”);
    driver = new FirefoxDriver();
    }
    //每个用例执行后会执行该方法
    @AfterMethod
    public void tearDown(){undefined
    //退出操作
    driver.quit();
    driver = null;
    }
    @Test
    public void startTest(){undefined
    //打开新窗口
    driver.get(url);
    }
    }

    各种浏览器比较↓

    Webdirver对浏览器的支持HtmlUnit Driver优点:HtmlUnit Driver不会实际打开浏览器,运行速度很快。对于用FireFox等浏览器来做测试的自动化测试用例,运行速度通常很慢,HtmlUnit Driver无疑是可以很好地解决这个问题。
    缺点:它对JavaScript的支持不够好,当页面上有复杂JavaScript时,经常会捕获不到页面元素。
    使用:
    WebDriver driver = new HtmlUnitDriver();

    FireFox Driver优点:FireFox Dirver对页面的自动化测试支持得比较好,很直观地模拟页面的操作,对JavaScript的支持也非常完善,基本上页面上做的所有操作FireFox Driver都可以模拟。
    缺点:启动很慢,运行也比较慢,不过,启动之后Webdriver的操作速度虽然不快但还是可以接受的,建议不要频繁启停FireFox Driver。
    使用:
    WebDriver driver = new FirefoxDriver();
    Firefox profile的属性值是可以改变的,比如我们平时可能需要通过代理上网,可以这样修改:
    FirefoxProfile profile = new FirefoxProfile();

    //使用profile

        ProfilesIni allProfiles = new ProfilesIni();
        FirefoxProfile profile = allProfiles.getProfile("default");
        driver = new FirefoxDriver(profile);

    // 使用代理

    profile.setPreference(“network.proxy.type”, 1);

    // http协议代理配置

    profile.setPreference(“network.proxy.http”, proxyIp);
    profile.setPreference(“network.proxy.http_port”, proxyPort);

    // 所有协议公用一种代理配置,如果单独配置,这项设置为false,再类似于http的配置

    profile.setPreference(“network.proxy.share_proxy_settings”, true);

    // 对于localhost的不用代理,这里必须要配置,否则无法和webdriver通讯

    profile.setPreference(“network.proxy.no_proxies_on”, “localhost”);

    // 以代理方式启动firefox

    FirefoxDriver ff  = new FirefoxDriver(profile);

    InternetExplorer Driver优点:直观地模拟用户的实际操作,对JavaScript提供完善的支持。
    缺点:是所有浏览器中运行速度最慢的,并且只能在Windows下运行,对CSS以及XPATH的支持也不够好。
    使用:
    WebDriver driver = new InternetExplorerDriver();

    元素操作↓

    查找元素

    使用操作如何找到页面元素Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找。下面介绍几种比较常用的方法。
    By ID假设页面写成这样:
    <input type=”text” name=”userName”  id=”user” />
    那么可以这样找到页面的元素:
    通过id查找:
    WebElement element = driver.findElement(By.id(“user”));
    By Name或通过name查找:
    WebElement element = driver.findElement(By.name(“userName”));
    By XPATH或通过xpath查找:
    WebElement element =driver.findElement(By.xpath(“//input[@id='user']“));
    By Class Name假设页面写成这样:

    <div class=”top”><span>Head</span></div><divclass=”top”><span>HeadName</span></div>
    可以通过这样查找页面元素:
    List<WebElement>top= driver.findElements(By.className(“top”));

    By Link Text假设页面元素写成这样:
    <a href=”http://www.baidu.com”>baidu</a>>
    那么可以通过这样查找:
    WebElement baidu=driver.findElement(By.linkText(“baidu”));

    输入框传值

    输入框(text field or textarea)   找到输入框元素:
    WebElement element = driver.findElement(By.id(“passwd-id”));
    在输入框中输入内容:
    element.sendKeys(“test”);
    将输入框清空:
    element.clear();
    获取输入框的文本内容:
    element.getText();

    下拉菜单

    下拉选择框(Select)找到下拉选择框的元素:
    Select select = new Select(driver.findElement(By.id(“select”)));
    选择对应的选择项:select.selectByVisibleText(“testName”);

    select.selectByValue(“name”);
    不选择对应的选择项:
    select.deselectAll();
    select.deselectByValue(“name”);
    select.deselectByVisibleText(“姓名”);
    或者获取选择项的值:
    select.getAllSelectedOptions();
    select.getFirstSelectedOption();

    单选框

    单选项(Radio Button)找到单选框元素:
    WebElement sex=driver.findElement(By.id(“sex”));

    选择某个单选项:

    sex.click();
    清空某个单选项:
    sex.clear();

    判断某个单选项是否已经被选择:

    sex.isSelected();

    复选框

    多选项(checkbox)多选项的操作和单选的差不多:
    WebElement area =driver.findElement(By.id(“area .”));
    area .click();
    area .clear();
    area .isSelected();
    area .isEnabled();

    按钮

    按钮(button)找到按钮元素:
    WebElement saveButton = driver.findElement(By.id(“save”));

    点击按钮:

    saveButton.click();

    判断按钮是否enable:

    saveButton.isEnabled ();

    左右选择框也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如:

    Select name= new Select(driver.findElement(By.id(“name”)));
    name.selectByVisibleText(“hellen”);
    WebElement addName=driver.findElement(By.id(“addButton”));
    addName.click();

    弹出框

    弹出对话框(Popup dialogs)Alert alert = driver.switchTo().alert();
    alert.accept();
    alert.dismiss();
    alert.getText();

    表单提交

    表单(Form)Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:
    WebElement sub= driver.findElement(By.id(“sub”));
    sub.click();

    sub.submit();//只适合于表单的提交

    上传附件

    上传文件 (Upload File)上传文件的元素操作:
    WebElement picFile = driver.findElement(By.id(“picFile ”));
    String filePath = “d:\\report\\600x600x0.jpg”;
    picFile .sendKeys(filePath);

    多窗口切换

    Windows 或 Frames之间的切换

    首先切换到默认的frame
    driver.switchTo().defaultContent();
    切换到某个frame:
    driver.switchTo().frame(“leftFrame”);
    从一个frame切换到另一个frame:
    driver.switchTo().frame(“mainFrame”);
    切换到某个window:
    driver.switchTo().window(“windowName”);

    导航

    导航 (Navigationand History)打开一个新的页面:
    driver.navigate().to(“http://www.baidu.com”);

    通过历史导航返回原页面:
    driver.navigate().forward();
    driver.navigate().back();

    以上为简单介绍了一下webDriver中常遇到的操作,有问题可以查阅官方的API文档

  • 相关阅读:
    读书笔记之 javascript 设计模式 工厂模式
    5分钟读书笔记之 设计模式 桥接模式
    读书笔记之 javascript 设计模式 组合模式
    响应式布局
    接收浏览器传值的方式
    AutoPoco的使用
    四种传值方式
    IIS本地服务器,设置IP地址问题
    MVC的小知识点
    MVC 生成Html字符串MvcHtmlString CacheHelper用法
  • 原文地址:https://www.cnblogs.com/soundcode/p/15878650.html
Copyright © 2020-2023  润新知