什么是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文档

WebDriver介绍相关推荐

  1. 【自动化测试爬虫系列】Selenium Webdriver 介绍

    一. Selenium Webdriver技术介绍 1. 简介 selenium Webdriver是一套针对不同浏览器而开发的web应用自动化测试代码库.使用这套库可以进行页面的交互操作,并且可以重 ...

  2. Python+Selenium 自动化测试 2. Webdriver API介绍

    目录 一 Webdriver介绍 二 webdriver实现的原理 三  API介绍 Webdriver 元素的查找的八种方式 find_element_by_id()  源码 find_elemen ...

  3. 3 WebDriver 和 WebDriver 父类

    文章目录 WebDriver __init__方法 create_options方法 execute_cdp_cmd方法 get_network_conditions方法 launch_app方法 q ...

  4. Selenium Webdriver Desired Capabilities

    前言 我们每一个的selenium测试都应该在指定的环境下运行,这个环境可以是web浏览器.移动设备.移动模拟器等等. 那怎么来指定我们的selenium测试脚本运行环境呢? 本次分享主要解决这个问题 ...

  5. python动态页面元素爬取_爬取动态网页python+Web kit

    上一篇文章爬取动态网页python+selenium+webdriver介绍了爬取动态网站的一种模拟浏览器的方法,该方法的优劣也很明显 优: 可以模拟任何人的操作,输入账号密码,点击登录等等操作 劣: ...

  6. python动态渲染抓取网页_爬取动态网页python+Web kit

    上一篇文章爬取动态网页python+selenium+webdriver介绍了爬取动态网站的一种模拟浏览器的方法,该方法的优劣也很明显 优: 可以模拟任何人的操作,输入账号密码,点击登录等等操作 劣: ...

  7. 正经网站爬虫实战,如何快速使用Selenium爬取租房信息

    租房信息爬虫实战 摘要 1.技术选型 1.1 Selenium 1.2 MySql 2 程序思路 3 程序实现(python selenium) 3.1 引入需要的包 3.2 初始化驱动和数据库连接 ...

  8. 爬虫漫游指南:无头浏览器puppeteer的检测攻防

    1. 引言 许多爬虫初学者在接触到无头浏览器的时候都会有一种如获至宝的感觉,仿佛看到了爬虫的终极解决方案.无论是所有爬虫教程中都会出现的PhantomJS.Selenium,亦或是相对冷门的Night ...

  9. 【软件测试】python+selenium自动化测试

    一.什么是自动化测试 自动化测试指软件测试的自动化,在预设状态下运行应用程序或者系统,预设条件包括正常和异常,最 后评估运行结果.将人为驱动的测试行为转化为机器执行的过程. 单元测试 java的单元测 ...

最新文章

  1. linux下各种颜色的文件表示的文件类型
  2. Android镜像文件的拆解
  3. Vi编辑器中查找替换
  4. 重磅发布 | 30+ 阿里巴巴云原生「顶流」,给你一堂《云原生技术实践公开课》
  5. java token跨域,java 允许跨域
  6. ExtJS4之helloworld
  7. sleek大气后台UI管理系统模板
  8. Sql Server函数全解一字符串函数
  9. Python学习 :文件操作
  10. oracle 日志解析工具,Oracle logminer 日志分析工具使用
  11. 技术交底书在专利申请文件撰写中的功用
  12. 微软将与美国第二大杂货连锁店展开合作 以抵抗亚马逊
  13. 前端,后端,前台,后台到底应该怎么理解。
  14. Linux man帮助文档
  15. 实数系基本定理证明第①波
  16. 计算机处理器缓存参数,如何查看CPU型号和主频、缓存、接口等参数
  17. Visual Studio Code修改主题背景颜色
  18. 数据压缩(一)——音频文件时域频域分析RGB文件三通道的熵
  19. 【观察】在UBBF 2021,看懂全光目标网的演进与创新
  20. Android Studio 1.5.1最新版下载地址

热门文章

  1. C++Miller Rabin算法的实现(附完整源码)
  2. QT的QMediaControl类的使用
  3. C语言的main函数到底怎么写的
  4. 初中计算机学情分析,初中信息技术教学计划
  5. 报时功能_现在的智能机都没有内置整点自动报时吗?锤子坚果手机SOS有!
  6. 「Docker」Docker教程+学习笔记
  7. 03_数据的特征抽取,sklearn特征抽取API,字典特征抽取DictVectorizer,文本特征抽取CountVectorizer,TF-IDF(TfidfVectorizer),详细案例
  8. Storm配置文件中主要参数配置说明
  9. IntelliJ Idea取消Colud not autowire.No
  10. svn数据仓库配置,权限配置