Selenium 2介绍(三)--Selenium WebDriver.docx_第1页
Selenium 2介绍(三)--Selenium WebDriver.docx_第2页
Selenium 2介绍(三)--Selenium WebDriver.docx_第3页
Selenium 2介绍(三)--Selenium WebDriver.docx_第4页
Selenium 2介绍(三)--Selenium WebDriver.docx_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Selenium WebDriver介绍WebDriverSelenium 2.0主要的特性就是与WebDriver API的集成。WebDriver旨在提供一个更简单,更简洁的编程接口以及解决一些Selenium-RC API的限制。Selenium-Webdriver更好的支持页面本身不重新加载而页面的元素改变的动态网页。WebDriver的目标是提供一个良好设计的面向对象的API,提供了对于现代先进web应用程序测试问题的改进支持。WebDriver与Selenium-RC相比如何驱动浏览器Selenium-WebDriver使用每个浏览器自身对自动化的支持来直接调用浏览器。这些直接调用怎么做取决于你所使用的浏览器。对于每个浏览器的Driver的信息,我们会在本章后面提供。对于那些熟悉Selenium-RC的人,这与你们以前做的很不同。Selenium-RC对于每个支持的浏览器采用相同的方式。当浏览器加载的时候,它“注入”浏览器的javascript功能,然后使用javascript来驱动浏览器内的应用程序。WebDriver不使用这个技术。再一次,它直接使用浏览器的内建自动化支持来驱动浏览器。WebDriver和Selenium-Server你可能需要或者可能不需要Selenium Server。取决于你打算如何使用Selenium-WebDriver。如果你只用WebDriver API你不需要Selenium-Server。如果你的浏览器和测试运行在同一机器,你的测试只使用WebDriver API,你不需要运行Selenium-Server,WebDriver会直接运行浏览器。但是有一些原因你需要使用Selenium-Serverl 你使用Selenium-Grid来在多个机器或者虚拟机中分布运行您的测试。l 您想连接一个远程的特定的浏览器l 你使用的不是Java,想使用HtmlUnitDriver设置一个Selenium-WebDriver项目安装Selenium意味着设置一个您可以用Selenium来写程序的开发项目。如何做取决于您开发环境的编程语言。Java最简单的方法是使用Maven来创建一个Selenium 2的Java项目。使用Maven的pom.xml(项目配置)文件,Maven会下载java绑定(Selenium2.0 java client library)和它的所有依赖并会为您创建项目。您这么做了之后,您可以导入这个maven项目到您喜欢的IDE,IntelliJ IDEA或者Eclipse。首先,创建一个目录来存放您的Selenium项目文件。然后使用Maven,您需要一个pom.xml文件。在您创建的目录中创建这个文件。可以使用文件编辑器来创建。您的pom.xml文件看起来像这样: 4.0.0 MySel20Proj MySel20Proj 1.0 org.seleniumhq.selenium selenium-java 2.24.1 com.opera operadriver com.opera operadriver 0.16 org.seleniumhq.selenium selenium-remote-driver 请确保您指定了最新的版本。在/download/maven.html 中检查最近的发布,在上面的pom.xml文件中修改相应的版本。现在,在命令行里,cd到你的项目目录下,执行下面的maven命令:mvn clean install这会下载selenium和它所有的依赖,并且会把它们添加到项目中。最后,导出您的项目到您偏爱的开发环境中。对于那些不熟悉的人,我们提供附录/docs/appendix_installing_java_driver_Sel20_via_maven.html#importing-maven-into-intellij-reference/docs/appendix_installing_java_driver_Sel20_via_maven.html#importing-maven-into-eclipse-reference从Selenium1.0的移植Migrating From Selenium RC to Selenium WebDriver用例子来介绍Selenium-WebDriver APIWebDriver是一个自动化测试Web应用的工具,特别是用来验证它们能否按预期运作。它的目标是提供一个友好的API,能够很容易探索和理解, 比selenium rc(1.0)的API更容易使用,这将有助于使您的测试更容易阅读和维护。它并不依赖于任何特定的测试框架,所以可以在一个单元测试或从一个普通的旧“Main”方法中使用它。本节介绍了WebDriver的API和帮助你开始熟悉它。首先设置一个WebDriver项目如果你还没有这么做。这是在前一节中描述的。您的项目设置好后,您可以看到WebDriver就和普通的Library一样工作:他完全是自包含的, 在使用它之前,你通常不需要记住要启动任何额外的进程或运行任何安装,这与selenium rc的代理服务器相反。注意:Chrome Driver,Opera Driver,Android Driver和iPhone Driver需要做一些额外的步骤。你现在可以开始写代码了。一个简单的方法是用这个示例来开始。在谷歌搜索术语“Cheese”然后把页面的标题输出到控制台。package org.openqa.selenium.example;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;public class Selenium2Example public static void main(String args) / Create a new instance of the Firefox driver / Notice that the remainder of the code relies on the interface, / not the implementation. WebDriver driver = new FirefoxDriver(); / And now use this to visit Google driver.get(); / Alternatively the same thing can be done like this / driver.navigate().to(); / Find the text input element by its name WebElement element = driver.findElement(B(q); / Enter something to search for element.sendKeys(Cheese!); / Now submit the form. WebDriver will find the form for us from the element element.submit(); / Check the title of the page System.out.println(Page title is: + driver.getTitle(); / Googles search is rendered dynamically with JavaScript. / Wait for the page to load, timeout after 10 seconds (new WebDriverWait(driver, 10).until(new ExpectedCondition() public Boolean apply(WebDriver d) return d.getTitle().toLowerCase().startsWith(cheese!); ); / Should see: cheese! - Google Search System.out.println(Page title is: + driver.getTitle(); /Close the browser driver.quit(); 在接下来的部分,您将会学到更多关于如何使用WebDriver比如在浏览器的历史中向前和向后导航,以及如何使用框架和窗口测试web站点。我们还提供一个更详细的讨论和示例。Selenium-WebDriver API命令和操作抓取页面您可能想用WebDriver做的第一件事情是导航到一个页面。通常通过调用“get”来做:driver.get();WebDriver可能等待或不等待页面加载取决于几个因素,包括OS /浏览器组合。在某些情况下, WebDriver可能会在页面完成, 或者甚至页面刚开始,加载之前就返回控制。为了保证健壮性,你需要使用Explicit和Implicit Waits等待页面中的元素在页面中存在。定位UI元素(WebElement)WebDriver可以在WebDriver实例本身或者在一个WebElement中定位元素。每种语言的绑定都暴露了一个”FindElement”或者”FindElements”的方法。第一个方法返回一个WebElement对象,否则抛出异常。后者返回一个WebElement的List,他可能返回空List如果DOM中没有元素匹配这个查询。“Find”方法使用一个定位器或者一个查询对象称为“By”。“By”的战略如下:By ID这是定位一个元素最有效的和优先的方法。常见的误区是UI开发人员在页面中使用非惟一id或可以自动生成id,都应该被避免。Html元素的类比自动生成的id更合适。如何查找元素的例子:.WebElement element = driver.findElement(By.id(coolestWidgetEvah);By Tag NameDom中元素的Tag名字.如何查找元素的例子:WebElement frame = driver.findElement(By.tagName(iframe);By Name通过匹配name属性来查找input元素。例子:WebElement cheese = driver.findElement(B(cheese);By Link Text通过匹配可见文字来查找link元素例子:cheeseWebElement cheese = driver.findElement(By.linkText(cheese);By Partial Link Text通过匹配部分的可见文字来查找link元素例子:search for cheeseWebElement cheese = driver.findElement(By.partialLinkText(cheese);By CSS就像名字所暗示的,这是一个css定位的策略。默认情况下,浏览器支持使用的。所以请参阅w3c css选择器中通常使用的css选择器列表,。如果一个浏览器本身不支持css的查询,就使用Sizzle。IE 6、7和FF3.0目前使用Sizzle的css查询引擎。注意不是所有浏览器都是一样的,在某个版本工作的css可能在某个版本不工作。例子:milkcheeseWebElement cheese = driver.findElement(By.cssSelector(#food span.dairy.aged);By XPATHWebDriver尽可能使用浏览器的原生XPath功能。在这些浏览器,没有本地XPath支持,我们提供了我们自己的实现。这可能会导致一些意想不到的行为,除非你知道各种xpath引擎的差异。DriverTag and Attribute NameAttribute ValuesNative XPath SupportHtmlUnit DriverLower-casedAs they appear in the HTMLYesInternet Explorer DriverLower-casedAs they appear in the HTMLNoFirefox DriverCase insensitiveAs they appear in the HTMLYes这是有点抽象,所以对于以下HTML:Java: List inputs = driver.findElements(By.xpath(/input);将会得到以下的结果:XPath expressionHtmlUnit DriverFirefox DriverInternet Explorer Driver/input1 (“example”)22/INPUT020有时HTML元素的属性不需要显式地声明,因为他们有已知的默认值。例如,“input”标签并不需要“type”属性,因为它默认为“text”。当您在WebDriver中使用xpath时,不应期望能够与这些隐式显示的属性匹配。使用Javascript您可以执行任意javascript来找到一个元素,只要你返回一个DOM元素,它将自动转换为一个WebElement对象。一个简单的例子,页面中jQuery加载:WebElement element = (WebElement) (JavascriptExecutor)driver).executeScript(return $(.cheese)0);找到页面中每个label的input元素。List labels = driver.findElements(By.tagName(label);List inputs = (List) (JavascriptExecutor)driver).executeScript( var labels = arguments0, inputs = ; for (var i=0; i labels.length; i+) + inputs.push(document.getElementById(labelsi.getAttribute(for); return inputs;, labels);用户输入-填写表单我们已经看到了如何为一个文本区输入文本或文本字段,但是其他的元素呢?你可以“toggle”复选框的状态,你可以使用“click“选择一个类似选项标记。处理”Select”标记并不太坏。WebElement select = driver.findElement(By.tagName(select);List allOptions = select.findElements(By.tagName(option);for (WebElement option : allOptions) System.out.println(String.format(Value is: %s, option.getAttribute(value); option.click();这回找到页面中的第一个”Select”元素,以此循环每个选项,打印出它们的值,并依次选择每个选项。你会注意到,这并不是最有效处理元素选择的方式。WebDriver的支持类中包括一个称为“Select”的类,提供了有用的方法与这些交互。Select select = new Select(driver.findElement(By.tagName(select);select.deselectAll();select.selectByVisibleText(Edam);这将取消选择所有选项,然后选择显示文本“Edam”的选项。一旦你完成填写表单,您可能想要提交它。办法之一就是找到“submit”按钮,点击它:driver.findElement(By.id(submit).click();另外,WebDriver在每个元素中有一个方便的方法“submit”。如果你对一个表单中的元素调用, WebDriver将会在DOM中查找,直到找到其所在的表单,然后调用提交。如果元素并不是在一个表单中,那么将抛出NoSuchElementException。element.submit();在Windows和Frames中移动某些Web应用有许多Frame或者多窗口。WebDriver支持用”switchTo”方法在这些窗口中移动。driver.switchTo().window(windowName);所有对driver的调用现在将被被定向到指定的窗口。但是你怎么知道窗口的名称吗?看看javascript或链接,打开它:Click here to open a new window或者,你可以通过一个“window handle”到“switchTo().window()”的方法。知道了这一点,它可以像这样遍历所有打开的窗口:for (String handle : driver.getWindowHandles() driver.switchTo().window(handle);您也可以从Frame switch到frame,或者iframedriver.switchTo().frame(frameName);它可以通过一个由点号分隔的路径来定位子frame,也可以通过索引来指定frame。driver.switchTo().frame(frameName.0.child);会switch到叫做“frameName”的frame中的第一个子frame中名为“child”的子frame。所有的frame都从头开始算起。弹出对话框从Selenium 2.0 beta 1开始,有一个支持弹出对话框的内建支持。在你触发了打开弹出框的动作之后,你可以通过以下语句来访问这个报警框:Alert alert = driver.switchTo().alert();这将返回当前打开的警报对象。这个对象可以accept, dismiss, 阅读其内容甚至输入一个提示。这个接口同样适用于alert,confirm,prompt。 参考JavaDocs或RubyDocs获取更多信息。导航:历史和地址早些时候,我们说导航到一个页面上使用“get”命令(driver.get( ),如您所见,WebDriver有一些更小的,面向任务的接口。 导航是一个有用的任务。因为加载一个页面是一个基本的要求, 该方法在WebDriver的主要接口中,但它只是一下语句的一个同义词: driver.navigate().to();再次重申:navigate().to()和“get()”做同样的事情。只是一个比另一个更容易书写。“navigate”借口也暴露了在浏览器的历史向前和向后移动的方法:driver.navigate().forward();driver.navigate().back();请注意,这个功能完全取决于底层的浏览器。当你调用这些方法时,如果你在使用另一个浏览器,它可能会发生一些意想不到的事情。Cookies在我们离开这些步骤之前,你也许会有兴趣了解如何使用cookie。首先,你需要在cookie有效的域中。如果你想在你开始于网站互动时,你的主页是需要一段时间来加载,那么一个替代方法是找到一个较小的网页,通常是404页很小(/some404page)。/ Go to the correct domaindriver.get();/ Now set the cookie. This ones valid for the entire domainCookie cookie = new Cookie(key, value);driver.manage().addCookie(cookie);/ And now output all the available cookies for the current URLSet allCookies = driver.manage().getCookies();for (Cookie loadedCookie : allCookies) System.out.println(String.format(%s - %s, loadedCookie.getName(), loadedCookie.getValue();/ You can delete cookies in 3 ways/ By namedriver.manage().deleteCookieNamed(CookieName);/ By Cookiedriver.manage().deleteCookie(loadedCookie);/ Or all of themdriver.manage().deleteAllCookies();改变User Agent这用Firefox Driver 很简单。FirefoxProfile profile = new FirefoxProfile();profile.setPreference(general.useragent.override, “Some UA string”); WebDriver driver = new FirefoxDriver(profile);拖拉下面是一个示例,使用操作类来执行一个拖放。Native Events必须被激活。WebElement element = driver.findElement(B(source);WebElement target = driver.findElement(B(target);(new Actions(driver).dragAndDrop(element, target).perform();Driver细节与权衡WebDriver是关键接口的名称,但有几种实现。这些包括:HtmlUnit Driver这是目前最快和最轻量级实现的WebDriver。顾名思义,这是基于HtmlUnit。是一个基于java没有GUI 的Web浏览器实现。对于任何语言绑定的(除了java) Selenium Server都需要使用这个Driver。用法WebDriver driver = new HtmlUnitDriver();好处:l 最快的WebDriver实现l 纯Java方案。所以是平台独立的。l 支持Javascript。坏处:l 无法模拟浏览器的Javascript行为。HtmlUnit Driver中的Javascript没有一个流行的浏览器使用HtmlUnit使用的 JavaScript引擎。如果你使用HtmlUnit测试JavaScript,结果可能不同于那些浏览器。当我们说“JavaScript“我们实际上意味着“JavaScript和DOM”。尽管DOM是由W3C定义的, 但每个浏览器在他们执行DOM和JavaScript互动的实现中都有自己的怪癖和差异。HtmlUnit有一个令人印象深刻的DOM的完整实现和对JavaScript具有良好的支持, 但它没有不同于其他任何浏览器: 它有自己的怪癖,与W3C标准和主要浏览器的DOM实现都有差异。尽管它能够模仿其他浏览器。用WebDriver,我们不得不做出选择; 我们应该启用JavaScript功能,使我们的团队面临风险,还是我们应该禁用JavaScript, 尽管我们知道有越来越多的网站,依靠JavaScript吗?我们采取了保守的方法, 当我们使用HtmlUnit时,在默认情况下禁用支持。在WebDriver和HtmlUnit的每一个版本,我们重新评估这个决定:我们希望在某种程度上在HtmlUnit默认启用JavaScript。启用JavascriptHtmlUnitDriver driver = new HtmlUnitDriver(true);这使HtmlUnitDriver模仿Firefox 3.6的javascript处理。Firefox Driver使用Firefox插件来控制Firefox浏览器。Firefox Profile从安装在机器上的Profile精简到只包括Selenium WebDriver.xpi(插件)。改变了几个设置的默认值(see the source to see which ones)FirefoxDriver能够运行和测试在Windows,Mac,Linux。目前支持版本为3.6,10,最新- 1,最新。用法WebDriver driver = new FirefoxDriver();好处:l 在真实浏览器中运行,支持Javascriptl 比Intener Explorer Driver快坏处:l 比HtmlUnitDriver慢。修改Firefox Profile假设您想修改User agent(如上所述),但你得到了一个Firefox Profile,其中包含许多有用的扩展。有两种方法可以获取这个Profile。假设这个Profile已经使用Firefox的配置管理器(Firefox -ProfileManager)创建:一ProfileIni allProfiles = new ProfilesIni();FirefoxProfile profile = allProfiles.getProfile(WebDriver);profile.setPreferences(foo.bar, 23);WebDriver driver = new FirefoxDriver(profile);另外,如果Firefox还没有被Firefox注册File profileDir = new File(path/to/top/level/of/profile);FirefoxProfile profile = new FirefoxProfile(profileDir);profile.addAdditionalPreferences(extraPrefs);WebDriver driver = new FirefoxDriver(profile);当我们开发Firefox Driver的特性时,我们暴露了能够使用它们的接口。例如,直到我们觉得本机事件在Firefox和Linux上稳定了,他们是默认禁用的。启用:FirefoxProfile profile = new FirefoxProfile();profile.setEnableNativeEvents(true);WebDriver driver = new FirefoxDriver(profile);信息参考Firefox section in the wiki page 得到更多最新的信息。Internet Explorer Driver这个Driver 是由一个.dll控制,只在windows操作系统中可用。每个Selenium的发布,它的核心功能都在IE6, 7, 8 在XP, 9 在Windows 7 中被测试。用法WebDriver driver = new InternetExplorerDriver();好处:l 在真实浏览器中运行,支持Javascript坏处:l 只能在Windows运行l 相对慢。l XPath在某些版本不是原生的支持。Sizzle被自动注入,所以比其他浏览器慢,比CSS选择器慢。l CSS在6和7版本不是原生支持,Sizzle被自动注入。l CSS 选择器是原生的,但那些浏览器不完全支持CSS3。信息参考Internet Explorer section of the wiki page 得到最新信息。请注意Required Configuration 部分。Chrome DriverChrome Driver由Chromium 项目本身维护和支持。WebDriver通过chromedriver的二进制文件使Chrome 工作(在Chrominum项目的下载页面中查找)。你需要有chromedriver和一个chrome浏览器安装。chromedriver需要被放置在你的系统的路径地方,以让WebDriver自动发现它。Chrome浏览器本身是由chromedriver在默认的安装路径中找到。而这些都可以被环境变量覆盖。请参阅the wiki获得更多信息。用法WebDriver driver = new ChromeDriver();好处:l 在真实浏览器中运行,支持Javascriptl 因为Chrome是基于Webkit的浏览器,Chrome Driver 可能允许您验证您的站点是否在Safari中工作。注意因为Chrome使用它自己的V8 Javascript引擎,而不是Safari的Nitro引擎,javascript的执行可能不同。坏处:l 比HtmlUnit Driver慢信息参考See our wiki得到最新信息。更多信息可以在downloads page 找到使用ChromeDriver下载Chrome Driver可执行文件,按照wiki中的指令运行。Opera Driver参考Opera Driver wiki articleiPhone Driver参考iPhone Driver wiki articleAndroid Driver参考Android Driver wiki article后端的替代方案:结合WebDriver和RC技术WebDriver-Backed Selenium-RCWebDriver的Java版本提供一种Selenium-RC API的实现。这意味着你可以用底层的WebDriver技术来使用Selenium-RC的API。这主要是为了提供向后兼容。他也允许你用WebDriver的技术使用已有的test suite。提供了Selenium到WebDriver的迁移路径。也允许你在一个test case中同时使用两套API。Selenium-WebDriver如下使用:/ You may use any WebDriver implementation. Firefox is used here as an exampleWebDriver driver = new FirefoxDriver();/ A base url, used by selenium to resolve relative URLs String baseUrl = ;/ Create the Selenium implementationSelenium selenium = new WebDriverBackedSelenium(driver, baseUrl);/ Perform actions with seleniumselenium.open();selenium.type(name=q, cheese);selenium.click(name=btnG);/ Get the underlying WebDriver implementation back. This will refer to the/ same WebDriver instance as the driver variable above.WebDriver driverInstance = (WebDriverBackedSelenium) selenium).getWrappedDriver();/Finally, close the browser. Call stop on the WebDriverBackedSelenium instance/instead of calling driver.quit(). Otherwise, the JVM will continue running after/the browser has been closed.selenium.stop();好处:l 允许同时使用WebDriver和Selenium的APIl 提供一个从Selenium RC API到WebDrive

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论