---
title: "Selenium用户指南 - 第四章 Selenium 2.0和WebDriver[4]"
author: "lsjlym"
date: "2012-02-18T00:44:00Z"
tags: []
slug: "selenium-selenium-2-0-webdriver-4"
draft: false
lastmod: "2015-09-08T20:25:16Z"
id: 2241840
url: "https://lsjlym.iteye.com/blog/2241840"
---

[目录](http://blog.csdn.net/planisnothing/article/details/7234926)[上一页](http://blog.csdn.net/planisnothing/article/details/7252944)[下一页](http://blog.csdn.net/planisnothing/article/details/7252949)

驱动器特性和权衡

支持WebDriver的Selenium-RC

Java版的WebDriver提供了一个Selenium RC API实现。这意味着在使用Selenium RC API时，使用潜在的WebDriver技术。这主要是为了提供向后的兼容性。它允许那些有现存的、使用Selenium RC API的测试集的用户，可以在外表下使用WebDriver。提供用于使迁移到Selenium-WebDriver的道路变得轻松。同样，这允许人们并行地，在一个相同的测试中使用两个API。

Selenium-WebDriver像这样使用：

// 你可以使用任何WebDriver实现。在这里Firefox被用于作为一个示例。

WebDriver driver = new FirefoxDriver();

// 一个“base url”，Selenium用于解析相对URL。

String baseUrl = "http://www.google.com";

// 创建Selenium实现

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

// 用Selenium执行动作

selenium.open("http://www.google.com");  
selenium.type("name=q", "cheese");  
selenium.click("name=btnG");

// 返回潜在的WebDriver实现。这将引用相同的WebDriver实例，如同上面的“driver”变量

WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();

// 最后，关闭浏览器。调用WebDriverBackedSelenium 的stop方法

// 替代调用driver.quit()。否则JVM会继续在浏览器已经关闭后运行

selenium.stop();

优点

\- 允许WebDriver和Selenium API并行地运行。

\- 提供一个简单的机制用于管理从Selenium RC API到WebDriver的迁移。

\- 不需要独立的Selenium RC服务器被运行。

缺点

\- 没有实现每个方法。

\- 更多的高级Selenium用法（使用“browserbot”或其他来自Selenium内核的、内置的Javascript方法）可能不工作。

\- 某些方法可能比较慢，由于潜在的实现上的差别

支持WebDriver

WebDriver不支持Selenium RC支持的所有浏览器，如此当使用WebDriver API时，为了提供那种支持，你可以充分利用SeleneseCommandExecutor。

下面的代码以这种方式支持Safari（确信取消弹出阻塞）

DesiredCapabilities capabilities = new DesiredCapabilities();  
capabilities.setBrowserName("safari");  
CommandExecutor executor = new SeleneseCommandExecutor(new URL("http://localhost:4444/"), new URL("http://www.google.com/"), capabilities);  
WebDriver driver = new RemoteWebDriver(executor, capabilities);

用这种方法目前有某些较多的限制，尤其是findElement不能如预期般工作。同样，因为我们正在使用Selenium内核驱动浏览器，你会受到Javascript沙盒的限制。

Selenium WebDriver wiki

你可以在WebDriver的wiki找到进一步的WebDriver资源。

下一步

这一章只是高级别的WebDriver和某些关键特征的浏览。一旦熟悉Selenium-WebDriver API，你就会想要学习如何去构造可维护和可扩展的测试集，并在AUT的功能频繁地变化时降低脆弱性。大多数的Selenium专家现在推荐的方法是使用页面对象设计模式（Page Object Design Pattern），以及可能的页面工厂（Page Factory）设计你的测试代码。Selenium-WebDriver提供对这个的支持，通过提供一个PageFactory类在Java和C#中。这个，以及其他的高级主题，被介绍在下一章。此外，为了获得这种技术的高级别描述，你可能希望看看[测试设计考虑]()一章。这些章节介绍了通过使测试代码更模块化来编写更可维护的测试。

© Copyright 2008-2012, Selenium Project. Last updated on Feb 02, 2012.

[目录](http://blog.csdn.net/planisnothing/article/details/7234926)[上一页](http://blog.csdn.net/planisnothing/article/details/7252944)[下一页](http://blog.csdn.net/planisnothing/article/details/7252949)