1.安装selenium webdriver(eclipse+jdk+testng+selenium webdriver2.20+firefox 10)
1、安装firefox,使用firefox10。确保firefox安装在默认环境下(不是的话会报错)。 2、安装jdk,确保安装了jdk,我使用是java。但selenium webdriver也支持其它语言,如ruby、python、C#等。 3、安装eclipse。
4、安装selenium webdriver(http://seleniumhq.org/download/下载selenium rc 2.21.0)。解压下载的selenium webdriver包,在eclipse中你建立的项目中导入所下载的包。(如下提示) 注:1.右键项目—选择build path选项—选择configure build path点击
2.选择右侧add external jars(如图)
3.找到所下载的selenium-server-standalone-2.21.0包,点击确定
4.点击ok,包就能导入项目
2.配置testng
1.介绍
TestNG是一个设计用来简化广泛的测试需求的测试框架,从单元测试(隔
离测试一个类)到集成测试(测试由有多个类多个包甚至多个外部框架组成的整 个系统,例如运用服务器)。
a. TestNG是一个设计用来简化广泛的测试需求的测试框架,从单元测试到 集成测试
这个是TestNG设计的出发点,不仅仅是单元测试,而且可以用于集成测试。 设计目标的不同,对比junit的只适合用于单元测试,TestNG无疑走的更远。 可以用于集成测试,这个特性是我选择TestNG的最重要的原因。
b. 测试的过程的三个典型步骤,注意和junit(4.0)相比,多了一个将测试 信息添加到testng.xml 文件或者build.xml
测试信息尤其是测试数据不再写死在测试代码中,好处就是修改测试数据
时不需要修改代码/编译了,从而有助于将测试人员引入单元测试/集成测试。
c. 基本概念,相比junit的TestCase/TestSuite,TestNG有
suite/test/test method 三个级别,即将test/test method 明确区分开了。
2.配置testng
1.Eclipse中点击Help->Install new software
2.点击Add 在Location输入http://beust.com/eclipse
3.选中Testng版本,点击Next,按照提示安装,安装完之后重启Eclipse
4.新建JavaProject,右键BuildPath,添加testng-5.11-jdk15.jar和eclipse-testng.jar 5.新建一个sum类,用来计算两整数之和,代码如下:
package com.hpp;
public class sum { private int no1; private int no2; private intmysum;
public int add(int no1,int no2){ mysum=no1+no2; return mysum; } }
6.再新建testng class
点击finish,代码如下 package com.test;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals; import com.hpp.sum;
public class NewTest {
private sum newSum=new sum();
@Test
public void f() {
intmysum=newSum.add(1, 2); assertEquals(3,mysum,\"Right\"); } }
testing,xml会自动配置好的,这里不用管 项目的文件结构如下:
7.在testing.xml右键点击RunAs->Testng Suite,即可看到结果
至此环境的搭建全部完成,下面来做第一个test。
3.第一个test
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstExampe { public static void main(String[] args) { WebDriver driver = new FirefoxDriver();
driver.get(\"http://www.google.com.hk\");
WebElement element = driver.findElement(By.name(\"q\")); element.sendKeys(\"hello Selenium!\"); element.submit(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
driver.quit(); }
正常运行后,这几行代码将会打开firefox浏览器,然后转跳到google首页。在搜索框中输入hello Selenium并提交搜索结果。
B对浏览器的简单操作
1.打开一个测试浏览器
对浏览器进行操作首先需要打开一个浏览器,接下来才能对浏览器进行操作。
Java代码
importjava.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; importorg.openqa.selenium.ie.InternetExplorerDriver;
public class OpenBrowsers { public static void main(String[] args) {
//打开默认路径的firefox WebDriver diver = new FirefoxDriver(); //打开指定路径的firefox,方法1 System.setProperty(\"webdriver.firefox.bin\Files\\\\Mozilla Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); //打开指定路径的firefox,方法2 File pathToFirefoxBinary = new File(\"D:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\"); FirefoxBinaryfirefoxbin = new FirefoxBinary(pathToFirefoxBinary); WebDriver driver1 = new FirefoxDriver(firefoxbin,null); //打开ie WebDriverie_driver = new InternetExplorerDriver();
//打开chrome System.setProperty(\"webdriver.chrome.driver\ System.setProperty(\"webdriver.chrome.bin\
\"C:\\\\Documents Settings\\\\gongjf\\\\Local Settings\"
+\"\\\\Application Data\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"); } }
and
2.打开1个具体的url
打开一个浏览器后,我们需要跳转到特定的url下,看下面代码: Java代码
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenUrl { public static void main(String []args){ String url = \"http://www.51.com\"; WebDriver driver = new FirefoxDriver(); //用get方法 driver.get(url); }
}
//用navigate方法,然后再调用to方法 driver.navigate().to(url);
3.如何关闭浏览器
测试完成后,需要关闭浏览器
Java代码
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CloseBrowser { public static void main(String []args){ String url = \"http://www.51.com\"; WebDriver driver = new FirefoxDriver(); driver.get(url); }
//用quit方法 driver.quit();
//用close方法 driver.close(); }
4.如何返回当前页面的url和title
有时候我们需要返回当前页面的url或者title做一些验证性的操作等。代码如下: Java代码
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GetUrlAndTitle { public static void main(String []args){ String url = \"http://www.google.com\"; WebDriver driver = new FirefoxDriver(); driver.get(url); //得到title String title = driver.getTitle();
//得到当前页面url String currentUrl = driver.getCurrentUrl();
//输出title和currenturl System.out.println(title+\"\\n\"+currentUrl); } }
5.其他方法
getWindowHandle() 返回当前的浏览器的窗口句柄 getWindowHandles() 返回当前的浏览器的所有窗口句柄 getPageSource() 返回当前页面的源码
从上面代码可以看出操作浏览器的主要方法都来自org.openqa.selenium.WebDriver这个接口中。看了一下源代码这些方法都是在org.openqa.selenium.remote.RemoteWebDriver这个类中实现的,然后不同浏览的driver类继承RemoteWebDriver。
C定位页面元素
selenium-webdriver提供了强大的元素定位方法,支持以下三种方法。 单个对象的定位方法 多个对象的定位方法 层级定位 定位单个元素
在定位单个元素时,selenium-webdriver提示了如下一些方法对元素进行定位。
By.className(className)) By.cssSelector(selector) By.id(id)
By.linkText(linkText) By.name(name) By.partialLinkText(linkText) By.tagName(name) By.xpath(xpathExpression)
注意:selenium-webdriver通过findElement()\\findElements()等find方法调用\"By\"对象来定位和查询元素。By类只是提供查询的方式进行分类。findElement返回一个元素对象否则抛出异常,findElements返回符合条件的元素 List,如果不存在符合条件的就返回一个空的list。
1.使用className进行定位
当所定位的元素具有class属性的时候我们可以通过classname来定位该元素。 下面的例子定位了51.com首页上class为\"username\"的li。 Java代码
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class ByClassName {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver(); driver.get(\"http://www.51.com\");
WebElement element = driver.findElement(By.className(\"username\")); System.out.println(element.getTagName());
} }
输出结果: Java代码
Li
2.使用id属性定位
51.com首页的帐号输入框的html代码如下: Java代码
在下面的例子中用id定位这个输入框,并输出其title,借此也可以验证代码是否工作正常。
Java代码
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ByUserId { /** * @paramargs */ public static void main(String[] args) { // TODO Auto-generated method stub WebDriverdr = new FirefoxDriver(); dr.get(\"http://www.51.com\");
WebElement element = dr.findElement(By.id(\"passport_51_user\")); System.out.println(element.getAttribute(\"title\")); } }
输出结果: Java代码
用户名/彩虹号/邮箱
3.使用name属性定位
51.com首页的帐号输入框的html代码如下:
Java代码
使用name定位
Java代码
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ByUserId { /** * @paramargs */ public static void main(String[] args) { // TODO Auto-generated method stub WebDriverdr = new FirefoxDriver(); dr.get(\"http://www.51.com\");
WebElement e = dr.findElement(By.name(\"passport_51_user\")); System.out.println(element.getAttribute(\"title\")); } }
输出结果: Java代码
用户名/彩虹号/邮箱
4.使用css属性定位
51.com首页的帐号输入框的html代码如下: Java代码
使用css定位 Java代码
WebElement e1 = dr.findElement(By.cssSelector(\"#passport_51_user\"));
5.使用 XPATH定位
51.com首页的帐号输入框的html代码如下: Java代码
通过xpath查找: Java代码
WebElement element =driver.findElement(By.xpath(\"//input[@id='passport_51_user']\"));
6.使用其他方式定位
在定位link元素的时候,可以使用link和link_text属性; 另外还可以使用tag_name属性定位任意元素;
7..定位多个元素
上面提到findElements()方法可以返回一个符合条件的元素List组。看下面例子。
Java代码
importjava.io.File; importjava.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver;
public class FindElementsStudy { /** * @author gongjf */ public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get(\"http://www.51.com\"); //定位到所有标签的元素,然后输出他们的id List 输出结果: Java代码 passport_cookie_login gourl passport_login_from passport_51_user passport_51_password passport_qq_login_2 btn_reg passport_51_ishidden passport_auto_login 上面的代码返回页面上所有input对象 8.层级定位 层级定位的思想是先定位父元素,然后再从父元素中精确定位出其我们需要选取的子元素。 层级定位一般的应用场景是无法直接定位到需要选取的元素,但是其父元素比较容易定位,通过定位父元素再遍历其子元素选择需要的目标元素,或者需要定位某个元素下所有的子元素。 下面的代码演示了如何使用层级定位class为\"login\"的div,然后再取得它下面的所有label,并打印出他们的文本 Java代码 importjava.io.File; importjava.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxBinary; importorg.openqa.selenium.firefox.FirefoxDriver; public class LayerLocator { /** * @author gongjf */ public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get(\"http://www.51.com\"); //定位class为\"login\"的div,然后再取得它下面的所有label,并打印出他们的值 WebElement element = driver.findElement(By.className(\"login\")); List 输出结果: Java代码 帐号: 密码: 隐身 下次自动登录 D 如何对页面元素进行操作 找到页面元素后,怎样对页面进行操作呢?我们可以根据不同的类型的元素来进行一一说明。 1.输入框(text field or textarea) 找到输入框元素: WebElement element = driver.findElement(By.id(\"passwd-id\")); 在输入框中输入内容: element.sendKeys(“test”); 将输入框清空: element.clear(); 获取输入框的文本内容: element.getText(); 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(); 对下拉框进行操作时首先要定位到这个下拉框,new 一个Selcet对象,然后对它进行操作 3. 单选项(Radio Button) 找到单选框元素: WebElementbookMode =driver.findElement(By.id(\"BookMode\")); 选择某个单选项: bookMode.click(); 清空某个单选项: bookMode.clear(); 判断某个单选项是否已经被选择: bookMode.isSelected(); 4.多选项(checkbox) 多选项的操作和单选的差不多: WebElement checkbox =driver.findElement(By.id(\"myCheckbox.\")); checkbox.click(); checkbox.clear(); checkbox.isSelected(); checkbox.isEnabled(); 5.按钮(button) 找到按钮元素: WebElementsaveButton = driver.findElement(By.id(\"save\")); 点击按钮: saveButton.click(); 判断按钮是否enable: saveButton.isEnabled (); 6.左右选择框 也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如: Select lang = new Select(driver.findElement(By.id(\"languages\"))); lang.selectByVisibleText(“English”); WebElementaddLanguage =driver.findElement(By.id(\"addButton\")); addLanguage.click(); 7.弹出对话框(Popup dialogs) Alert alert = driver.switchTo().alert(); alert.accept(); alert.dismiss(); alert.getText(); 后面有具体的例子解释~ 8.表单(Form) Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以: WebElement approve = driver.findElement(By.id(\"approve\")); approve.click(); 或 approve.submit();//只适合于表单的提交 9.上传文件 (Upload File) 上传文件的元素操作: WebElementadFileUpload = driver.findElement(By.id(\"WAP-upload\")); String filePath = \"C:\est\\\dfile\\\\media_ads\\\est.jpg\"; adFileUpload.sendKeys(filePath); 10.拖拉(Drag andDrop) WebElement element =driver.findElement(By.name(\"source\")); WebElement target = driver.findElement(By.name(\"target\")); (new Actions(driver)).dragAndDrop(element, target).perform(); 11.导航 (Navigationand History) 打开一个新的页面: driver.navigate().to(\"http://www.example.com\"); 通过历史导航返回原页面: driver.navigate().forward(); driver.navigate().back(); Eiframe的处理 有时候我们在定位一个页面元素的时候发现一直定位不了,反复检查自己写的定位器没有任何问题,代码也没有任何问题。这时你就要看一下这个页面元素是否在一个iframe中,这可能就是找不到的原因之一。如果你在一个default content中查找一个在iframe中的元素,那肯定是找不到的。反之你在一个iframe中查找另一个iframe元素或default content中的元素,那必然也定位不到。 selenium webdriver中提供了进入一个iframe的方法: WebDriverorg.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId) 也提供了一个返回default content的方法: WebDriverorg.openqa.selenium.WebDriver.TargetLocator.defaultContent() 这样使我们面对iframe时可以轻松应对。 以下面的html代码为例,我们看一下处现iframe。 Html代码 main.html frame.html Java代码 importorg.openqa.selenium.By; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.firefox.FirefoxDriver; public class FameStudy { public static void main(String[] args) { WebDriverdr = new FirefoxDriver(); String url = \"\\\\Your\\\\Path\\\o\\\\main.html\"; dr.get(url); //在default content定位id=\"id1\"的div dr.findElement(By.id(\"id1\")); //此时,没有进入到id=\"frame\"的frame中时,以下两句会报错 dr.findElement(By.id(\"div1\"));//报错 dr.findElement(By.id(\"input1\"));//报错 //进入id=\"frame\"的frame中,定位id=\"div1\"的div和id=\"input1\"的输入框。 dr.switchTo().frame(\"frame\"); dr.findElement(By.id(\"div1\")); dr.findElement(By.id(\"input1\")); //此时,没有跳出frame,如果定位default content中的元素也会报错。 dr.findElement(By.id(\"id1\"));//报错 //跳出frame,进入default content;重新定位id=\"id1\"的div dr.switchTo().defaultContent(); dr.findElement(By.id(\"id1\")); } } 小结: switch_to方法会new1个TargetLocator对象,使用该对象的frame方法可以将当前识别的”主体”移动到需要定位的frame上去。 F 如何得到弹出窗口 在selenium 1.X里面得到弹出窗口是一件比较麻烦的事,特别是新开窗口没有id、name的时候。在selenium webdriver中得到新开窗口相对简单的多,它无关新开窗口的id、name等属性。以下面的html为例: Html代码 test.html 下面的代码演示了如何去得到弹出的新窗口 Java代码 importjava.util.Iterator; importjava.util.Set; importorg.openqa.selenium.By; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.firefox.FirefoxDriver; public class PopupWindowTest { /** * @author gongjf */ public static void main(String[] args) { System.setProperty(\"webdriver.firefox.bin\Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); String url =\"\\\\Your\\\\Path\\\o\\\\main.html\"; dr.get(url); dr.findElement(By.id(\"51\")).click(); //得到当前窗口的句柄 Files\\\\Mozilla } } String currentWindow = dr.getWindowHandle(); //得到所有窗口的句柄 Set 输出结果: title,url = 51.com 真人配对玩游戏,http://www.51.com/ 小结: 捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。( 在上面的代码里,使用windowhandle方法来获取当前浏览器窗口的句柄,使用了windowhandles方法获取所有弹出的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。 在获取新弹出窗口的句柄后,使用switchto.window(newwindow_handle)方法,将新窗口的句柄作为参数传入既可捕获到新窗口了。 如果想回到以前的窗口定位元素,那么再调用1次switch_to.window方法,传入之前窗口的句柄既可达到目的。 G如何处理alert、confirm、prompt对话框 alert、confirm、prompt这样的js对话框在selenium1.X时代也是难啃的骨头,常常要用autoit来帮助处理。 试用了一下selenium webdriver中处理这些对话框十分方便简洁 Html代码 Dialogs.html 你的名字'); document.write(name) \"/> 以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字。 selenium webdriver处理这些弹层的代码如下: Java代码 importorg.openqa.selenium.Alert; importorg.openqa.selenium.By; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.firefox.FirefoxDriver; public class DialogsStudy { /** * @author gongjf */ public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty(\"webdriver.firefox.bin\Files\\\\Mozilla Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); String url = \"file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html\";// \"/Your/Path/to/main.html\" dr.get(url); //点击第一个按钮,输出对话框上面的文字,然后叉掉 dr.findElement(By.id(\"alert\")).click(); Alert alert = dr.switchTo().alert(); String text = alert.getText(); System.out.println(text); alert.dismiss(); //点击第二个按钮,输出对话框上面的文字,然后点击确认 dr.findElement(By.id(\"confirm\")).click(); Alert confirm = dr.switchTo().alert(); String text1 = confirm.getText(); System.out.println(text1); confirm.accept(); //点击第三个按钮,输入你的名字,然后点击确认,最后 dr.findElement(By.id(\"prompt\")).click(); Alert prompt = dr.switchTo().alert(); String text2 = prompt.getText(); System.out.println(text2); prompt.sendKeys(\"jarvi\"); prompt.accept(); } } 小结: 从以上代码可以看出dr.switchTo().alert();这句可以得到alert\\confirm\\prompt对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有: getText() 得到它的文本值 accept() 相当于点击它的\"确认\" dismiss() 相当于点击\"取消\"或者叉掉对话框 sendKeys() 输入值,这个alert\\confirm没有对话框就不能用了,不然会报错。 H如何操作cookies Web 测试中我们经常会接触到Cookies,一个Cookies主要属性有”所在域、name、value、有效日期和路径\下面来讲一下怎么操作Cookies Java代码 importjava.util.Set; importorg.openqa.selenium.Cookie; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.firefox.FirefoxDriver; public class CookiesStudy { /** * @author gongjf */ public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty(\"webdriver.firefox.bin\Files\\\\Mozilla Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); dr.get(\"http://www.51.com\"); //增加一个name = \"name\的cookie Cookie cookie = new Cookie(\"name\ dr.manage().addCookie(cookie); //得到当前页面下所有的cookies,并且输出它们的所在域、name、value、有效日期和路径 Set } 小结: 上面的代码首先在页面中增加了一个cookie,然后遍历页面的所有cookies,并输出他们的主要属性。最后就是三种删除cookie的方法。 I 如何等待页面元素加载完成 web的自动化测试中,我们经常会遇到这样一种情况:当我们的程序执行时需要页面某个元素,而此时这个元素还未加载完成,这时我们的程序就会报错。怎么办?等待。等待元素出现后再进行对这个元素的操作。 在selenium-webdriver中我们用两种方式进行等待:明确的等待和隐性的等待。 明确的等待 明确的等待是指在代码进行下一步操作之前等待某一个条件的发生。最不好的情况是使用Thread.sleep()去设置一段确认的时间去等待。但为什么说最不好呢?因为一个元素的加载时间有长有短,你在设置sleep的时间之前要自己把握长短,太短容易超时,太长浪费时间。selenium webdriver提供了一些方法帮助我们等待正好需要等待的时间。利用WebDriverWait类和ExpectedCondition接口就能实现这一点。 下面的html代码实现了这样的一种效果:点击click按钮5秒钟后,页面上会出现一个红色的div块。我们需要写一段自动化脚本去捕获这个出现的div,然后高亮之。 Html代码 Wait.html 下面的代码实现了高亮动态生成的div块的功能: Java代码 importorg.openqa.selenium.By; importorg.openqa.selenium.JavascriptExecutor; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.WebElement; importorg.openqa.selenium.firefox.FirefoxDriver; importorg.openqa.selenium.support.ui.ExpectedCondition; importorg.openqa.selenium.support.ui.WebDriverWait; public class WaitForSomthing { /** * @author gongjf */ public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty(\"webdriver.firefox.bin\Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); String url = \"file:///C:/Documents and /selenium_test/Wait.html\";// \"/Your/Path/to/Wait.html\" dr.get(url); WebDriverWait wait = new WebDriverWait(dr,10); wait.until(new ExpectedCondition Files\\\\Mozilla Settings/gongjf/桌面 publicWebElement apply(WebDriver d) { returnd.findElement(By.id(\"b\")); }}).click(); WebElement element = dr.findElement(By.cssSelector(\".red_box\")); ((JavascriptExecutor)dr).executeScript(\"arguments[0].style.border = yellow\\\"\ } } \\\"5px solid 上面的代码WebDriverWait类的构造方法接受了一个WebDriver对象和一个等待最长时间(10秒)。然后调用until方法,其中重写了ExpectedCondition接口中的apply方法,让其返回一个WebElement,即加载完成的元素,然后点击。默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到有成功的返回,当然如果超过设定的值还没有成功的返回,将抛出异常。 隐性等待 隐性等待是指当要查找元素,而这个元素没有马上出现时,告诉WebDriver查询Dom一定时间。默认值是0,但是设置之后,这个时间将在WebDriver对象实例整个生命周期都起作用。上面的代码就变成了这样: Java代码 importjava.util.concurrent.TimeUnit; importorg.openqa.selenium.By; importorg.openqa.selenium.JavascriptExecutor; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.WebElement; importorg.openqa.selenium.firefox.FirefoxDriver; importorg.openqa.selenium.support.ui.ExpectedCondition; importorg.openqa.selenium.support.ui.WebDriverWait; public class WaitForSomthing { /** * @author gongjf */ public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty(\"webdriver.firefox.bin\Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); //设置10秒 dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); Files\\\\Mozilla String url = \"file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Wait.html\";// \"/Your/Path/to/Wait.html\" dr.get(url); //注释掉原来的 /*WebDriverWait wait = new WebDriverWait(dr,10); wait.until(new ExpectedCondition 小结: 两种方法任选其一 J 如何利用selenium-webdriver截图 在自动化测试中常常会用到截图功能。最近用了一下selenium-webdriver的截图功能还算不错,可以截取页面全图,不管页面有多长。 下面的代码演示了如何使用webdriver进行截图: Java代码 importjava.io.File; importjava.io.IOException; importorg.apache.commons.io.FileUtils; importorg.openqa.selenium.OutputType; importorg.openqa.selenium.TakesScreenshot; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.firefox.FirefoxDriver; public class ShotScreen { /** * @author gongjf * @throws IOException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException { System.setProperty(\"webdriver.firefox.bin\Files\\\\Mozilla Firefox\\\\firefox.exe\"); WebDriverdr = new FirefoxDriver(); dr.get(\"http://www.51.com\"); //这里等待页面加载完成 Thread.sleep(5000); } } //下面代码是得到截图并保存在D盘下 File screenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenShotFile, new File(\"D:/test.png\")); K 封装与重用 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; importjava.util.List; importjava.util.NoSuchElementException; importjava.util.concurrent.TimeUnit; importorg.openqa.selenium.By; importorg.openqa.selenium.WebElement; importorg.openqa.selenium.remote.RemoteWebDriver; importorg.openqa.selenium.support.ui.WebDriverWait; import com.drutt.mm.end2end.data.TestConstant; public class WebDriverAction { //protected WebDriverdriver; protectedRemoteWebDriverdriver; protectedWebDriverWaitdriverWait; protectedbooleanisWebElementExist(By selector) { try { driver.findElement(selector); return true; } catch(NoSuchElementException e) { return false; } } protectedStringgetWebText(By by) { try { returndriver.findElement(by).getText(); } catch (NoSuchElementException e) { return \"Textnot existed!\"; } } protectedvoidclickElementContainingText(By by, String text){ List protectedStringgetLinkUrlContainingText(By by, String text){ List for(WebElement e:subscribeButton){ if(e.getText().contains(text)){ url =e.getAttribute(\"href\"); break; } } returnurl; } protected void click(Byby){ driver.findElement(by).click(); driver.manage().timeouts().implicitlyWait(TestConstant.WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS); } protectedStringgetLinkUrl(By by){ returndriver.findElement(by).getAttribute(\"href\"); } protected void sendKeys(Byby, String value){ driver.findElement(by).sendKeys(value); } 小结: 按照上面的例子你可以对各个方法进行封装,使自己的代码更加简洁! L 在selenium2.0中使用selenium1.0的API Selenium2.0中使用WeDriver API对页面进行操作,它最大的优点是不需要安装一个selenium server就可以运行,但是对页面进行操作不如selenium1.0的Selenium RC API那么方便。Selenium2.0提供了使用Selenium RC API的方法: // 我用火狐浏览器作为例子 WebDriver driver = new FirefoxDriver(); String baseUrl =\"http://www.google.com\"; Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl); // 执行selenium命令 selenium.open(\"http://www.google.com\"); selenium.type(\"name=q\selenium.click(\"name=btnG\"); WebDriverdriverInstance = ((WebDriverBackedSelenium)selenium).getUnderlyingWebDriver(); selenium.stop(); 我分别使用WebDriver API和SeleniumRC API写了一个Login的脚本,很明显,后者的操作更加简单明了。 WebDriver API写的Login脚本: public void login() { driver.switchTo().defaultContent(); driver.switchTo().frame(\"mainFrame\"); WebElementeUsername= waitFindElement(By.id(\"username\")); eUsername.sendKeys(manager@ericsson.com); WebElementePassword= 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\ selenium.type(\"password\ selenium.click(\"loginButton\"); } 因篇幅问题不能全部显示,请点此查看更多更全内容