Webdriver API中文版

1.1   下载selenium2.0的lib包

http://code.google.com/p/selenium/downloads/list

官方UserGuide:http://seleniumhq.org/docs/

1.2   用webdriver打开一个浏览器

我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器。但是做页面的测试,速度通常很慢,严重影 响持续集成的速度,这个时候建议使用HtmlUnit,不过HtmlUnitDirver运行时是看不到界面的,对调试就不方便了。使用哪种浏览器,可以 做成配置项,根据需要灵活配置。

  1. 打开firefox浏览器:

//Create a newinstance of the Firefox driver

WebDriver driver = newFirefoxDriver();

  1. 打开IE浏览器

//Create a newinstance of the Internet Explorer driver

WebDriver driver = newInternetExplorerDriver ();

  1. 打开HtmlUnit浏览器

//Createa new instance of the Internet Explorer driver

WebDriverdriver = new HtmlUnitDriver();

 

1.3   打开测试页面

对页面对测试,首先要打开被测试页面的地址(如:http://www.google.com),web driver 提供的get方法可以打开一个页面:

// And now use thedriver to visit Google

driver.get("http://www.google.com");

1.4   GettingStarted

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 voidmain(String[] args) {

// Create a newinstance of the Firefox driver

// Notice that theremainder of the code relies on the interface,

// not the implementation.

WebDriver driver = newFirefoxDriver();

// And now use this tovisit Google

driver.get("http://www.google.com");

// Alternatively thesame thing can be done like this

// driver.navigate().to("http://www.google.com");

// Find the text inputelement by its name

WebElement element =driver.findElement(By.name("q"));

// Enter something tosearch for

element.sendKeys("Cheese!");

// Now submit the form.WebDriver will find the form for us from the element

element.submit();

// Check the title ofthe page

System.out.println("Page title is: " + driver.getTitle());

// Google's search isrendered dynamically with JavaScript.

// Wait for the pageto load, timeout after 10 seconds

(newWebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {

public Booleanapply(WebDriver d) {

returnd.getTitle().toLowerCase().startsWith("cheese!");

}

});

// Should see:"cheese! - Google Search"

System.out.println("Page title is: " + driver.getTitle());

//Close the browser

driver.quit();

}

}

第2章        Webdirver对浏览器的支持

2.1   HtmlUnit Driver

优点:HtmlUnit Driver不会实际打开浏览器,运行速度很快。对于用FireFox等浏览器来做测试的自动化测试用例,运行速度通常很慢,HtmlUnit Driver无疑是可以很好地解决这个问题。

缺点:它对JavaScript的支持不够好,当页面上有复杂JavaScript时,经常会捕获不到页面元素。

使用:

WebDriver driver = new HtmlUnitDriver();

2.2   FireFox Driver

优点:FireFox Dirver对页面的自动化测试支持得比较好,很直观地模拟页面的操作,对JavaScript的支持也非常完善,基本上页面上做的所有操作FireFox Driver都可以模拟。

缺点:启动很慢,运行也比较慢,不过,启动之后Webdriver的操作速度虽然不快但还是可以接受的,建议不要频繁启停FireFox Driver。

使用:

WebDriver driver = new FirefoxDriver();

Firefox profile的属性值是可以改变的,比如我们平时使用得非常频繁的改变useragent的功能,可以这样修改:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UAstring");
WebDriver driver = new FirefoxDriver(profile);

2.3   InternetExplorer Driver

优点:直观地模拟用户的实际操作,对JavaScript提供完善的支持。

缺点:是所有浏览器中运行速度最慢的,并且只能在Windows下运行,对CSS以及XPATH的支持也不够好。

使用:

WebDriver driver = new InternetExplorerDriver();

第3章        使用操作

3.1  如何找到页面元素

Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找。下面介绍几种比较常用的方法。

3.1.1 By ID

假设页面写成这样:

<input type="text" name="passwd"id="passwd-id" />

 

那么可以这样找到页面的元素:

通过id查找:

WebElement element = driver.findElement(By.id("passwd-id"));

3.1.2 By Name

或通过name查找:

WebElement element = driver.findElement(By.name("passwd"));

3.1.3 By XPATH

或通过xpath查找:

WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));

3.1.4 By Class Name

假设页面写成这样:

<div class="cheese"><span>Cheddar</span></div><divclass="cheese"><span>Gouda</span></div>

可以通过这样查找页面元素:

List<WebElement>cheeses = driver.findElements(By.className("cheese"));

3.1.5 By Link Text

假设页面元素写成这样:

<ahref="http://www.google.com/search?q=cheese">cheese</a>>

那么可以通过这样查找:

WebElement cheese =driver.findElement(By.linkText("cheese"));

3.2  如何对页面元素进行操作

找到页面元素后,怎样对页面进行操作呢?我们可以根据不同的类型的元素来进行一一说明。

3.2.1 输入框(text field or textarea)

找到输入框元素:

WebElement element = driver.findElement(By.id("passwd-id"));

在输入框中输入内容:

element.sendKeys(“test”);

将输入框清空:

element.clear();

获取输入框的文本内容:

element.getText();

3.2.2 下拉选择框(Select)

找到下拉选择框的元素:

Select select = new Select(driver.findElement(By.id("select")));

 
  选择对应的选择项:

select.selectByVisibleText(“mediaAgencyA”);

select.selectByValue(“MA_ID_001”);

 

不选择对应的选择项:

select.deselectAll();

select.deselectByValue(“MA_ID_001”);

select.deselectByVisibleText(“mediaAgencyA”);

或者获取选择项的值:

select.getAllSelectedOptions();

select.getFirstSelectedOption();

3.2.3 单选项(Radio Button)

找到单选框元素:

WebElement bookMode =driver.findElement(By.id("BookMode"));

选择某个单选项:

bookMode.click();

清空某个单选项:

bookMode.clear();

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

bookMode.isSelected();

3.2.4 多选项(checkbox)

多选项的操作和单选的差不多:

WebElement checkbox =driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

3.2.5 按钮(button)

找到按钮元素:

WebElement saveButton = driver.findElement(By.id("save"));

点击按钮:

saveButton.click();

判断按钮是否enable:

saveButton.isEnabled ();

3.2.6 左右选择框

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

Select lang = new Select(driver.findElement(By.id("languages")));

lang.selectByVisibleText(“English”);

WebElement addLanguage =driver.findElement(By.id("addButton"));

addLanguage.click();

3.2.7 弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();

3.2.8 表单(Form)

Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:

WebElement approve = driver.findElement(By.id("approve"));

approve.click();

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

3.2.9 上传文件 (Upload File)

上传文件的元素操作:

WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));

String filePath = "C:\test\\uploadfile\\media_ads\\test.jpg";

adFileUpload.sendKeys(filePath);

3.2.10  Windows 和 Frames之间的切换

一般来说,登录后建议是先:

driver.switchTo().defaultContent();

切换到某个frame:

driver.switchTo().frame("leftFrame");

从一个frame切换到另一个frame:

driver.switchTo().frame("mainFrame");

切换到某个window:

driver.switchTo().window("windowName");

3.2.11   拖拉(Drag andDrop)

WebElement element =driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();

3.2.12   导航 (Navigationand History)

打开一个新的页面:

driver.navigate().to("http://www.example.com");

通过历史导航返回原页面:

driver.navigate().forward();

driver.navigate().back();

3.3   高级使用

3.3.1 改变user agent

User Agent的设置是平时使用得比较多的操作:

FirefoxProfile profile = new FirefoxProfile();

profile.addAdditionalPreference("general.useragent.override","some UA string");

WebDriver driver = new FirefoxDriver(profile);

3.3.2 读取Cookies

我们经常要对的值进行读取和设置。

增加cookie:

// Now set the cookie. This one's valid for the entire domain

Cookie cookie = new Cookie("key", "value");

driver.manage().addCookie(cookie);

获取cookie的值:

// And now output all the available cookies for the current URL

Set<Cookie> allCookies = driver.manage().getCookies();

for (Cookie loadedCookie : allCookies) {

System.out.println(String.format("%s -> %s",loadedCookie.getName(), loadedCookie.getValue()));

}

根据某个cookie的name获取cookie的值:

driver.manage().getCookieNamed("mmsid");

删除cookie:

// You can delete cookies in 3 ways

// By name

driver.manage().deleteCookieNamed("CookieName");

// By Cookie

driver.manage().deleteCookie(loadedCookie);

// Or all of them

driver.manage().deleteAllCookies();

3.3.3 调用Java Script

Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"

+ value + "');})()");

3.3.4 Webdriver截图

如果用webdriver截图是:

driver = webdriver.Firefox()
driver.save_screenshot("C:\error.jpg")

3.3.5 页面等待

因为Load页面需要一段时间,如果页面还没加载完就查找元素,必然是查找不到的。最好的方式,就是设置一个默认等待时间,在查找页面元素的时候如果找不到就等待一段时间再找,直到超时。

Webdriver提供两种方法,一种是显性等待,另一种是隐性等待。

显性等待:

WebDriver driver =new FirefoxDriver();

driver.get("http://somedomain/url_that_delays_loading");

WebElementmyDynamicElement = (new WebDriverWait(driver, 10))

.until(newExpectedCondition<WebElement>(){

@Override

public WebElementapply(WebDriver d) {

returnd.findElement(By.id("myDynamicElement"));

}});

隐性等待:

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get("http://somedomain/url_that_delays_loading");

WebElement myDynamicElement =driver.findElement(By.id("myDynamicElement"));

第4章        RemoteWebDriver

当本机上没有浏览器,需要远程调用浏览器进行自动化测试时,需要用到RemoteWebDirver.

4.1   使用RemoteWebDriver

import java.io.File;

import java.net.URL;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.remote.Augmenter;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

public void myTest()throws Exception {

WebDriver driver = newRemoteWebDriver(

new URL("http://localhost:4446/wd/hub"),

DesiredCapabilities.firefox());

driver.get("http://www.google.com");

// RemoteWebDriverdoes not implement the TakesScreenshot class

// if the driver doeshave the Capabilities to take a screenshot

// then Augmenter willadd the TakesScreenshot methods to the instance

WebDriveraugmentedDriver = new Augmenter().augment(driver);

File screenshot =((TakesScreenshot)augmentedDriver).

getScreenshotAs(OutputType.FILE);

}

}

4.2   SeleniumServer

在使用RemoteDriver时,必须在远程服务器启动一个SeleniumServer:

java -jar selenium-server-standalone-2.20.0.jar -port 4446

4.3   How to setFirefox profile using RemoteWebDriver

profile = new FirefoxProfile();

profile.setPreference("general.useragent.override",testData.getUserAgent());

capabilities = DesiredCapabilities.firefox();

capabilities.setCapability("firefox_profile", profile);

driver = new RemoteWebDriver(new URL(“http://localhost:4446/wd/hub”),capabilities);

driverWait = new WebDriverWait(driver,TestConstant.WAIT_ELEMENT_TO_LOAD);

driver.get("http://www.google.com");

第5章        封装与重用

WebDriver对页面的操作,需要找到一个WebElement,然后再对其进行操作,比较繁琐:

// Find the text inputelement by its name

WebElement element = driver.findElement(By.name("q"));

// Enter something to search for

element.sendKeys("Cheese!");

我们可以考虑对这些基本的操作进行一个封装,简化操作。比如,封装代码:

protected void sendKeys(Byby, String value){

driver.findElement(by).sendKeys(value);

}

那么,在测试用例可以这样简化调用:

sendKeys(By.name("q"),”Cheese!”);

类似的封装还有:

package com.drutt.mm.end2end.actions;

import java.util.List;

import java.util.NoSuchElementException;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import com.drutt.mm.end2end.data.TestConstant;

public class WebDriverAction {

//protected WebDriverdriver;

protected RemoteWebDriverdriver;

protected WebDriverWaitdriverWait;

protected booleanisWebElementExist(By selector) {

try {

driver.findElement(selector);

return true;

} catch(NoSuchElementException e) {

return false;

}

}

protected StringgetWebText(By by) {

try {

return driver.findElement(by).getText();

} catch (NoSuchElementException e) {

return "Textnot existed!";

}

}

protected voidclickElementContainingText(By by, String text){

List<WebElement>elementList = driver.findElements(by);

for(WebElement e:elementList){

if(e.getText().contains(text)){

e.click();

break;

}

}

}

protected StringgetLinkUrlContainingText(By by, String text){

List<WebElement>subscribeButton = driver.findElements(by);

String url = null;

for(WebElement e:subscribeButton){

if(e.getText().contains(text)){

url =e.getAttribute("href");

break;

}

}

return url;

}

protected void click(Byby){

driver.findElement(by).click();

driver.manage().timeouts().implicitlyWait(TestConstant.WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS);

}

protected StringgetLinkUrl(By by){

return driver.findElement(by).getAttribute("href");

}

protected void sendKeys(Byby, String value){

driver.findElement(by).sendKeys(value);

}

第6章        在selenium2.0中使用selenium1.0的API

Selenium2.0中使用WeDriver API对页面进行操作,它最大的优点是不需要安装一个selenium server就可以运行,但是对页面进行操作不如selenium1.0的Selenium RC API那么方便。Selenium2.0提供了使用Selenium RC API的方法:

// You may use any WebDriver implementation. Firefox is used hereas an example

WebDriver driver = new FirefoxDriver();

// A "base url", used by selenium to resolve relativeURLs

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

// Create the Selenium implementation

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

// Perform actions with selenium

selenium.open("http://www.google.com");

selenium.type("name=q", "cheese");

selenium.click("name=btnG");

// Get the underlying WebDriver implementation back. This willrefer to the

// same WebDriver instance as the "driver" variableabove.

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

//Finally, close thebrowser. Call stop on the WebDriverBackedSelenium instance

//instead of callingdriver.quit(). Otherwise, the JVM will continue running after

//the browser has beenclosed.

selenium.stop();

我分别使用WebDriver API和SeleniumRC API写了一个Login的脚本,很明显,后者的操作更加简单明了。

WebDriver API写的Login脚本:

public void login() {

driver.switchTo().defaultContent();

driver.switchTo().frame("mainFrame");

WebElement eUsername= waitFindElement(By.id("username"));

eUsername.sendKeys(manager@ericsson.com);

WebElement ePassword= waitFindElement(By.id("password"));

ePassword.sendKeys(manager);

WebElementeLoginButton = waitFindElement(By.id("loginButton"));

eLoginButton.click();

}

SeleniumRC API写的Login脚本:

public void login() {

selenium.selectFrame("relative=top");

selenium.selectFrame("mainFrame");

selenium.type("username","manager@ericsson.com");

selenium.type("password","manager");

selenium.click("loginButton");

}

Webdriver API中文版的更多相关文章

  1. 转:python webdriver API 之操作测试对象

    一般来说,所有有趣的操作与页面交互都将通过 WebElement 接口,包括上一节中介绍的对象定位,以及本节中需要介绍的常对象操作.webdriver 中比较常用的操作元素的方法有下面几个: cle ...

  2. Webdriver API (二)

    (转载) 1.3 打开测试页面 对页面对测试,首先要打开被测试页面的地址(如:http://www.google.com),web driver 提供的get方法可以打开一个页面: // And no ...

  3. JAVA JDK 1.6 API中文版.CHM打开chm提示,“ 已取消到该网页的导航”

    JAVA  JDK 1.6 API中文版.CHM打开chm提示,“ 已取消到该网页的导航” silent fish 装了win7后,打开chm文件,发现很多在xp系统打开正常的chm文件竟然出现问题, ...

  4. Zepto,Zepto API 中文版,Zepto 中文手册,Zepto API,Zepto API 中文版,Zepto 中文手册,Zepto API 1.0, Zepto API 1.0 中文版,Zepto 1.0 中文手册,Zepto 1.0 API-translate by yaotaiyang

    Zepto,Zepto API 中文版,Zepto 中文手册,Zepto API,Zepto API 中文版,Zepto 中文手册,Zepto API 1.0, Zepto API 1.0 中文版,Z ...

  5. selenium2(WebDriver) API

    selenium2(WebDriver) API 作者:Glen.He出处:http://www.cnblogs.com/puresoul/  1.1  下载selenium2.0的包 官方downl ...

  6. Selenium2+Python:Webdriver API速记手册

    由于web自动化常常需要控制浏览器行为和操作页面元素,相关函数又比较多,于是再此记下一份Webdriver API查阅文档以备不时之需. 参考:虫师<Selenium2自动化测试实战>,和 ...

  7. webdriver API中文文档

    1.1   下载selenium2.0的lib包 http://code.google.com/p/selenium/downloads/list 官方UserGuide:http://seleniu ...

  8. python+selenium自动化软件测试(第2章):WebDriver API

    2.1 操作元素基本方法 前言前面已经把环境搭建好了,从这篇开始,正式学习selenium的webdriver框架.我们平常说的 selenium自动化,其实它并不是类似于QTP之类的有GUI界面的可 ...

  9. Selenium WebDriver Api 知识梳理

    之前一直没有系统的梳理WebDriver Api的相关知识,今天借此机会整理一下. 1.页面元素定位 1.1.8种常用定位方法 # id定位 driver.find_element_by_id() # ...

随机推荐

  1. Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 不支持“variant”数据类型。

    mybatis执行sqlserver的sql报错 com.microsoft.sqlserver.jdbc.SQLServerException: 不支持“variant”数据类型. at com.m ...

  2. 在弹框中获取foreach中遍历的id值,并传递给地址栏。

    1.php有时候我们需要再弹框中获取foreach中遍历的数据(例如id),在弹框中点击按钮并传递给地址栏跳转.那么应该怎么做呢. 2. 点击取现按钮,如果没有设置密码->弹框 3. 点击去设置 ...

  3. python单下划线、双下划线、头尾双下划线说明:

      单下划线.双下划线.头尾双下划线说明: __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的. _foo: 以单下划线开头的表示的是 protected 类 ...

  4. The parameter to the method is the basic data type

    package method.invocation; public class TheParameterToTheMethodIsTheBasicDataType { public static vo ...

  5. java indexOf 和 split的用法

    1.java 的 indexOf 方法 ,如果存在 则 指定的字符串的开始位置,如果不存在 则返回-1: 2.java 的 split的方法:将一个字符串分割为子字符串,然后将结果作为字符串数组返回. ...

  6. .net core系列之《从源码对Configuration的底层运行机制进行分析》

    通过对Configuration源代码的分析从而来自定义一个配置数据源 1.用反编译工具来看看AddJsonFile()这个方法究竟干了什么,源代码如下: public static IConfigu ...

  7. java笔记--增加虚拟机内存

    --如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3877243.html "谢谢-- 为避免大型应用程序因虚拟机内存不足而无法 ...

  8. netstat 常用方法

    netstat简介 netstat是一个监控TCP/IP网络的非常有用的工具,它可以显示路由表,实际的网络连接以及每一个网络接口设备的状态信息,netstat用于显示与IP,TCP,UDP和ICMP协 ...

  9. ORA-12514

    ORA-12514: TNS:listener does not currently know of service requested in connect descriptor 监听器目前不知道在 ...

  10. 无法用Put方式请求发布在IIS中的WebAPI

    WebApi程序发布到IIS上后,无法使用Put的方式进行请求,错误信息如下:             原因和解决方案:   在IIS中默认不支持Put请求和Delete请求,因为IIS中注册的Web ...