selenium_2.0安装使用说明2
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Selenium2.0使用说明
目录
第1章Webdirver基础 (1)
1.1 介绍WebDriver (1)
1.2 安装selenium webdriver (1)
1.2.1安装jdk并配置环境变量 (1)
1.2.2安装Firefox,Selenium IDE,Firebug和xpath checker (1)
1.2.3安装eclipse (2)
1.2.4安装selenium webdriver (6)
1.3 工具使用 (6)
1.3.1 Selenium-IDE使用 (6)
1.3.2 Firebug的使用 (7)
1.3.3 xpath checker的使用 (8)
1.3.4 Selenium 2.0的使用 (9)
第2章Webdirver对浏览器的支持 (10)
2.1 HtmlUnit Driver (10)
2.2 FireFox Driver (10)
2.3 InternetExplorer Driver (10)
第3章对浏览器的简单操作 (11)
3.1 用webdriver打开一个浏览器 (11)
3.2 打开测试页面 (11)
3.3 关闭浏览器 (12)
3.4 返回当前页面的url 和title (12)
第4章使用操作 (12)
4.1 如何找到页面元素 (12)
4.1.1 By ID (12)
4.1.2 By Name (13)
4.1.3 By XPATH (13)
4.1.4 By Class Name (13)
4.1.5 By Link Text (13)
4.2 如何对页面元素进行操作 (14)
4.2.1 输入框(text field or textarea) (14)
4.2.2 下拉选择框(Select) (14)
4.2.3 单选项(Radio Button) (14)
4.2.4 多选项(checkbox) (15)
4.2.5 按钮(button) (15)
4.2.6 左右选择框 (15)
4.2.7 弹出对话框(Popup dialogs) (15)
4.2.8 表单(Form) (16)
4.2.9 上传文件(Upload File) (16)
4.2.10 Windows 和Frames之间的切换 (16)
4.2.11 拖拉(Drag andDrop) (16)
4.2.12 导航(Navigationand History) (16)
4.2.13 模拟鼠标、键盘的操作 (17)
4.2.14 控制滚动体 (18)
4.2.15 将IE最大化 (19)
4.3 高级使用 (20)
4.3.1 改变user agent (20)
4.3.2 读取Cookies (20)
4.3.3 调用Java Script (21)
4.3.4 Webdriver截图 (21)
4.3.5 页面等待 (21)
第5章RemoteWebDriver (22)
5.1 使用RemoteWebDriver (22)
5.2 SeleniumServer (22)
5.3 How to setFirefox profile using RemoteWebDriver (23)
第6章常见问题总结 (23)
6.1 选择options-->format,显示的是:want the formats back?click to read more (23)
6.2 插入等待时间 (23)
6.3点击a元素弹出窗口 (23)
第1章Webdirver基础
1.1 介绍WebDriver
Selenium 2.0主要的特性就是与WebDriver API的集成。
WebDriver
简洁的编程接口以及解决一些Selenium-RC API的限制。
Selenium-Webdriver更好的支持页面本身不重新加载而页面的元素改变的动态网页。
WebDriver的目标是提供一个良好设计的面向对象的API web应用程序测试问题的改进支持。
Selenium Webdriver 支持很多语言,如:C#,Java,Python,Ruby 等,本文使用java。
1.2 安装selenium webdriver
1.2.1安装jdk并配置环境变量
jdk安装jdk需要1.6版本及以上的,安装目录为默认路径。
jdk下载地址:/technetwork/java/javase/downloads/index.html
环境变量配置:
CLASSPATH=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jarJAVA_HOME=C:\Program Files\Java\jdk1.6.0_10PATH=%JAVA_HOME%\bin
1.2.2安装Firefox,Selenium IDE,Firebug和xpath checker
安装FireFox
Firefox版本有一定限制,需要和selenium IDE相匹配。
下载地址:/download/
安装Selenium IDESelenium IDE是基于FIREFOX浏览器的一个插件,提供GUI界面来运行Selenium测试。
Selenium IDE提供脚本录制和回放功能,可以将用户在浏览器中执行的操作记录下来,生成各种形式的脚本,可以将这些脚本保存供selenium使用。
Selenium IDE主要是用在Selenium 1.0中,在Selenium 2.0中基本不使用。
1)下载Selenim IDE下载地址:/download/
2)安装:直接把下载的Selenium IDE文件拖到FireFox浏览器窗口中,按提示操作即可安装成功。
安装Firebug:
1)打开Firefox浏览器
2)点击菜单“工具(T)”,下拉列表中选择“附加组件”。
3)“获取附加组件”
4)在搜索里输入“firebug”,稍等即可。
5)点击“安装”
6)OK,重启浏览器即可。
安装xpath checker
1)打开Firefox浏览器
2)点击菜单“工具(T)”,下拉列表中选择“附加组件”。
3)“获取附加组件”
4)在搜索里输入“xpath checker”,稍等即可。
5)点击“安装”
6)OK,重启浏览器即可。
1.2.3安装eclipse
一、安装eclipse,安装在默认安装目录下。
1、JDK1.6
2、Eclipse:Version: Kepler Service Release 1,下载地址:
/downloads/
3、Selenium:selenium-java-2.39.0.zip,下载地址:
/p/selenium/downloads/list
解压selenium-java包,这个包里面包含四部分,如下图:
二、新建一个Java Project:
1、然后把上面解压出来的文件拷到新建的project目录下(copy-paste),目录结构如下图:
2、添加build path,项目目录右键-->Build Path--> config build path-->Java Build Path-->Libraries-->Add JARs
把libs文件夹下的jar包全部添加上,再添加selenium-java-2.39.0和
selenium-java-2.39.0-srcs(Add JARs)
3、添加完之后目录结构如下图,多了Referenced Libraries,这里就是上面那一步添加进去的jar包:
4、关联webdriver的源码:右键点击
->properties->
5、导入junit4:
右键项目名称->build path->add libariry->Junit->Junit4->finish
1.2.4安装selenium webdriver
1)下载:IEDriverServer_Win32_2.39.0.zip
下载地址:/p/selenium/downloads/list
官方UserGuide:/docs/
2)下载:selenium-java-2.39.0.jar和selenium-java-2.39.0.zip(使用java语言的下载该包)。
下载地址:/download/
3)解压下载的selenium-java-2.39.0.zip文件
1.3 工具使用
1.3.1 Selenium-IDE使用
1)Firefox工具栏,打开Selenium-IDE插件,如下图:
2)在“Base URL”中输入需要录制脚本的网址地址,然后点击界面中右上角红色录制按钮(开始录制、停止录制都是此按钮),如下图。
3)录制完成后,点击回放按钮可以对刚刚录制的脚本进行回放,这里可以调整回放速度。
回放按钮就是上图中的绿色三角按钮。
4)还可以将录制的脚本转换成C#,Java,PHP,Ruby,Prel,Groovy,Python等语言,如下图所示。
转换完以后可以直接复制到Eclipse中使用,在Selenium 1.0中稍加修改就可使用,在Selenium 2.0则不能直接使用,只能手动编制。
1.3.2 Firebug的使用
打开Firebug有两种基本的方法:
1)当需要获取页面上元素的属性时,可以使用Firebug进行获取,例如下图所示输入框:
获取方法:右击输入框,在菜单中选择“使用firebug查看元素”
此时将会在页面下方出现该元素的属性,如下图所示:
然后右击“编辑”后面的内容,在菜单中选择“复制xpath”,即可使用。
2)Firebug也可以通过点击Firefox浏览器上的“查看”菜单->“Firebug”->“打开Firebug”进行打开。
1.3.3 xpath checker的使用
元素的属性还可以通过xpath checker来查看。
对于上面百度输入框的属性可以通过右击并选择菜单中的“view xpath“按钮
此时会打开如下窗口,“XPath”中的内容就是该输入框的属性,在下面会显示对应的元素。
1.3.4 Selenium
2.0的使用
1)在Eclipse里新建一个project,然后引用selenium-java-2.39.0.zip解压后的selenium-java-2.39.0.jar。
2)新建一个class“Seleniumcn”把代码贴进去,如果代码没错误就可以运行了。
例如下面:package辅助测试;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Seleniumcn {
public static void main(String[] args) {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory","co .apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
WebDriver driver = new FirefoxDriver();
driver.get("");
WebElement element = driver.findElement(("q"));
element.sendKeys("hello Selenium!");
element.submit();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
正常运行后,这几行代码将会打开firefox 浏览器,然后转跳到google 首页。
在搜索框中输入hello Selenium 并提交搜索结果。
等待3 秒后会在命令行打印出当前页面的title,输出如下:
Page title is: hello Selenium! - Google 搜索
并关闭ff 浏览器。
第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的操作速度虽然不快但还是可以接受的。
使用:
WebDriver driver = new FirefoxDriver();
2.3 InternetExplorer Driver
优点:直观地模拟用户的实际操作,对JavaScript提供完善的支持。
缺点:是所有浏览器中运行速度最慢的,并且只能在Windows下运行,对CSS以及XPATH
的支持也不够好。
使用:
WebDriver driver = new InternetExplorerDriver();
第3章对浏览器的简单操作
3.1 用webdriver打开一个浏览器
我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器,还支持HtmlUnit浏览器,打开语句为:
打开firefox浏览器:
//Create a newinstance of the Firefox driver
如果你的本地firefox是默认路径安装的话,如下方式即可启动浏览器
WebDriver driver = new FirefoxDriver();
b.如果不是默认路径安装,需要先将firefox.exe配置到系统变量中去,如下:
System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla
Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
打开IE浏览器
//Create a newinstance of the Internet Explorer driver
由于ie,chrome浏览器的driverServer是由他们自己管理的,我们需要下载相应的驱动,注意区分32位和64位,”src\\main\\resources\\IEDriver.exe"为IEDriver.exe的存储路径System.setProperty("webdriver.ie.driver", "src\\main\\resources\\IEDriver.exe");
WebDriver driver = newInternetExplorerDriver ();
打开HtmlUnit浏览器
//Createa new instance of the Internet Explorer driver
WebDriverdriver = new HtmlUnitDriver();
打开Chrome浏览器
//Createa new instance of the Chromer driver
System.setProperty("webdriver.chrome.driver", "src\\main\\resources\\chromedriver.exe"); WebDriver driver = new ChromeDriver();
3.2 打开测试页面
对页面测试,首先要打开被测试页面的地址(如:),web driver 提供的get方法可以打开一个页面:
// And now use the driver to visit Google
driver.get("http://www. ");
3.3 关闭浏览器
测试完成后,需要结束IEDriverServer 进程
driver.close();
测试完成后,需要关闭浏览器
//Close the browser
driver.quit();
3.4 返回当前页面的url 和title
有时候我们需要返回当前页面的url 或者title 做一些验证性的操作等。
代码如
下:
//得到title
String title = driver.getTitle();
//得到当前页面url
String currentUrl = driver.getCurrentUrl();
//输出title 和currenturl
System.out.println(title+"\n"+currentUrl);
第4章使用操作
4.1 如何找到页面元素
Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name 查找。
下面介绍几种比较常用的方法。
4.1.1 By ID
假设页面写成这样:
<input type="text" name="passwd"id="passwd-id" />
那么可以这样找到页面的元素:
通过id查找:
WebElement element = driver.findElement(By.id("passwd-id"));
4.1.2 By Name
或通过name查找:
WebElement element = driver.findElement(("passwd"));
4.1.3 By XPATH
或通过xpath查找:
WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));
4.1.4 By Class Name
假设页面写成这样:
<div class="cheese">
<span>Cheddar</span>
</div>
<div class="cheese">
<span>Gouda</span>
</div>
可以通过这样查找页面元素:
List<WebElement>cheeses = driver.findElements(By.className("cheese"));
4.1.5 By Link Text
假设页面元素写成这样:
<ahref="/search?q=cheese">cheese</a>>
那么可以通过这样查找:
WebElement cheese =driver.findElement(By.linkText("cheese"));
4.1.6 By cssSelector
页面元素写成这样:
<div class="x-grid-cell-inner " style="text-align: left; ;">
<img class="x-action-col-icon x-action-col-0
roleAuthorityIcon" data-qtip="配置资源权限
" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAA LAAAAAABAAEAAAICRAEAOw==" alt="">
</div>
可以通过这样查找:
WebElemen element=driver.findElements( By.cssSelector("img.roleAuthorityIcon")).get(0);
4.1.7 Switchto
4.2 如何对页面元素进行操作
找到页面元素后,怎样对页面进行操作呢?我们可以根据不同的类型的元素来进行一一说明。
4.2.1 输入框(text field or textarea)
找到输入框元素:
WebElement element = driver.findElement(By.id("passwd-id"));
在输入框中输入内容:
element.se ndKeys(“test”);
将输入框清空:
element.clear();
获取输入框的文本内容:
element.getText();
4.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();
4.2.3 单选项(Radio Button)
找到单选框元素:
WebElement bookMode =driver.findElement(By.id("BookMode"));
选择某个单选项:
bookMode.click();
清空某个单选项:
bookMode.clear();
判断某个单选项是否已经被选择:
bookMode.isSelected();
4.2.4 多选项(checkbox)
多选项的操作和单选的差不多:
WebElement checkbox =driver.findElement(By.id("myCheckbox.")); checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();
4.2.5 按钮(button)
找到按钮元素:
WebElement saveButton = driver.findElement(By.id("save"));
点击按钮:
saveButton.click();
判断按钮是否enable:
saveButton.isEnabled ();
4.2.6 左右选择框
也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。
例如:Select lang = new Select(driver.findElement(By.id("languages")));
lang.selectByVisibleText(“English”);
WebElement addLanguage =driver.findElement(By.id("addButton")); addLanguage.click();
4.2.7 弹出对话框(Popup dialogs)
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
4.2.8 表单(Form)
Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:WebElement approve = driver.findElement(By.id("approve"));
approve.click();
或
approve.submit();//只适合于表单的提交
4.2.9 上传文件(Upload File)
上传文件的元素操作:
WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));
String filePath = "C:\test\\uploadfile\\media_ads\\test.jpg";
adFileUpload.sendKeys(filePath);
4.2.10 Windows 和Frames之间的切换
一般来说,登录后建议是先:
driver.switchTo().defaultContent();
切换到某个frame:
driver.switchTo().frame("leftFrame");
从一个frame切换到另一个frame:
driver.switchTo().frame("mainFrame");
切换到某个window:
driver.switchTo().window("windowName");
4.2.11 拖拉(Drag andDrop)
WebElement element =driver.findElement(("source"));
WebElement target = driver.findElement(("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();
4.2.12 导航(Navigationand History)
打开一个新的页面:
driver.navigate().to("");
通过历史导航返回原页面:
driver.navigate().forward();
driver.navigate().back();
4.2.13 模拟鼠标、键盘的操作
Actions action = new Actions(driver);
鼠标左键点击:
Actions action = new Actions(driver);
action.click(driver.findElement(By.xpath(xpath)));
左键点击是普通常用的方法,前面已经介绍过一种更简单的方法:
Driver driver=new Driver();
driver.findElement(By.xpath(xpath)).click();
2、鼠标左键双击:
Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.xpath(xpath)));
3、鼠标左键按下操作:
Actions action = new Actions(driver);
action.clickAndHold(driver.findElemen(By.xpath(xpath)));
4、鼠标左键移动到元素操作:
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath(xpath)));
5、鼠标右键点击操作:
Actions action = new Actions(driver) ;
action.contextClick(driver.findElement(By.xpath(xpath)));
6、组合的鼠标操作(将目标元素拖拽到指定的元素上):
Actions action = new Actions(driver);
action.dragAndDrop(driver.findElement(By.xpath(xpath)),driver.findElement(By.xpath(xpath)));
7、组合的鼠标操作(将目标元素拖拽到指定的元素上):
Actions action = new Actions(driver);
action.dragAndDrop(driver.findElement(By.xpath(xpath)),xOffset,yOffset);
代码演示:
driver.get("");
driver.findElement(("wd")).sendKeys("林丹");
//点击操作
driver.findElement(by.id("su")).click();
driver.navigate().back();
Actions action=new Actions(driver);
action.click(driver.findElement(by.id("su")));
//拖拽选择操作,鼠标按住不放,进行拖拽选择,然后释放鼠标,需要三个动作
action.clickAndHold(driver.findElement(By.id("1"))).moveToElement(driver.findElement(By.id("3") )).perform();
action.release();
//拖拽元素,将一个元素拖拽到另一个元素上,然后释放鼠标(略)
键盘的模拟操作,包括普通按键,比如enter、backspace、tab等,还包括四个修饰键(Modifier Keys),分别是Caps Lock,Control,Option,Command。
普通按键使用时,直接使用sendkeys(theKeys)就可以,如按下enter键:
action.sendKeys(Keys.ENTER).perform();
修饰键一般使用时,是和别的按键配合使用的,比如快捷键ctrl+F4,这时就得使用keyDown(theKeys)、keyUp(theKeys)来操作,代码如下:
driver.get("");
driver.findElement(("wd")).sendKeys("林丹");
Actions action=new Actions(driver);
//输入框中输入内容,然后点击回车进行百度
action.sendKeys(Keys.ENTER).perform();
//使用快捷键alt+f4关闭窗口(但是该方法不稳定,时行时不行,不行居多)
action.keyDown(keys.ATL).keyDown(keys.F4).keyUp(keys.ALT).perform();
//使用ctrl+a全选
driver.findElement(By.id("kw")).click();
action.sendKeys(Keys.CONTROL+"a").perform();
Tips:
1、拖拽选择时,使用clickAndHold和moveToElement时,会受到鼠标所在位置的影响,所以尽量是两个方法一起使用;
2、拖拽元素时,dragAndDrop方法,我没有找到实现的场景,所以没有写代码试验;
3、直接按下普通按键时,直接使用sendkeys(theKeys)方法就能够实现;
4、需要使用修饰键时,需要连贯动作中应该使用keydown和keyup方法;
action.keyDown(keys.ATL).sendKeys(keys.F4).keyUp(keys.ALT).perform();//这是不能实现alt+f4关闭窗口的效果的,只能实现单独按f4的效果
5、对于一些快捷键,如ctrl+a,可以直接sendkeys(Keys.CONTROL+"a")
6、对于这些操作,使用perform()方法进行执行
4.2.14 控制滚动条
1.控制滚动条到顶部
JavascriptExecutor jse=(JavascriptExecutor) driver;
jse.executeScript("document.documentElement.scrollTop=0");
2.将滚动条滚到适当的位置
public static void setScroll(WebDriver driver,int height){
try {
String setscroll = "document.documentElement.scrollTop=" + height;
JavascriptExecutor jse=(JavascriptExecutor) driver;
jse.executeScript(setscroll);
} catch (Exception e) {
System.out.println("Fail to set the scroll.");
}
}
4.2.15 将IE最大化
1 封装一个函数
public static void maxBrowser(WebDriver driver){
try {
String maxBroswer = "if (window.screen) {window.moveTo(0, 0);" + "window.resizeTo(window.screen.availWidth,window.screen.availHeight);}";
JavascriptExecutor jse=(JavascriptExecutor) driver;
jse.executeScript(maxBroswer);
} catch (Exception e) {
System.out.println("Fail to Maximization browser");
}
}
2 直接使用
driver.manage().window().maximize();
.2.16 获取红框显示的提示内容
页面写成这样:<input id="textfield-2678-inputEl" class="x-form-field x-form-required-field x-form-text x-form-invalid-field" type="text" autocomplete="off" style="width: 100%; -moz-user-select:
text;" name="workyearName" size="1" aria-invalid="true" data-errorqtip="<ul><li>工作日名称不允许为空!</li></ul>">
可以通过这种方式实现:
String
attibute=driver.findElement(("workyearName")).getAttribute("da ta-errorqtip");
if(!"".equals(attibute)){
int index=attibute.indexOf("li>");
int end=stIndexOf("</li");
attibute=attibute.substring(index+3, end);
assertEquals("工作日名称不允许为空!", attibute);
}else{
verificationErrors.append("workyearName verfication error");
}
4.3 高级使用
4.3.1 改变user agent
User Agent的设置是平时使用得比较多的操作:
FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference("eragent.override","some UA string");
WebDriver driver = new FirefoxDriver(profile);
4.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();
4.3.3 调用Java Script
Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"+ value + "');})()");
4.3.4 Webdriver截图
如果用webdriver截图是:
driver = webdriver.Firefox();
public void takeScreenShot(String name){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("e:\\Learning\\"+ name));
} catch (IOException e) {
e.printStackTrace();
}
}
4.3.5 页面等待
因为Load页面需要一段时间,如果页面还没加载完就查找元素,必然是查找不到的。
最好的方式,就是设置一个默认等待时间,在查找页面元素的时候如果找不到就等待一段时间再找,直到超时。
Webdriver提供两种方法,一种是显性等待,另一种是隐性等待。
显性等待:
WebDriver driver =new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(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"));
第5章RemoteWebDriver
当本机上没有浏览器,需要远程调用浏览器进行自动化测试时,需要用到RemoteWebDirver.
5.1 使用RemoteWebDriver
import java.io.File;
import .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("");
// 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);
}
}
5.2 SeleniumServer
在使用RemoteDriver时,必须在远程服务器启动一个SeleniumServer:
java -jar selenium-server-standalone-2.25.0.jar -port 4446
5.3 How to setFirefox profile using RemoteWebDriver
profile = new FirefoxProfile();
profile.setPreference("eragent.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("");
第6章常见问题总结
6.1 选择options-->format,显示的是:want the formats
back?click to read more
问题:录完后,想转换成Junit4,选择options-->format,发现显示的是:want the formats back?click to read more,找不到所要选择的Junit 4
解决办法:选择options-->options-->General-->勾中enable experimental feature即可
6.2 插入等待时间
问题:回放失败,发现装载页面需要时间,需要插入pause,时间5000毫秒
解决办法:在table界面选中某行,右键选择insert new command,即在该行之前插入,然后在新行的command输入pause,value栏输入5000
Wait?
6.3点击a元素弹出窗口
问题:点击元素为tr[@id='Cq8']/td/table/tbody/tr[2]/td[4]/a/img,弹出新窗口
解决办法:
JavascriptExecutor javascriptExecutor = (JavascriptExecutor)driver;
jaascriptExecutor.executeScript("$('#Cq8>td>table>tbody>tr>td>a').trigger('click')");
不懂de代码
byCssSelector('input[node-type="username"]');
Maven项目配置前的准备
第一步:配置settings.xml
为settings.xml找一个放置路径,一般为“C:\Documents and Settings\Administrator\.m2”(亦可指定其它的路径)
第二步:修改JAR包仓库保存位置
打开settings.xml定位到如图所示的位置修改工具包的保存路径
如果不想进行修改则调整为如下图所示,会默认保存到settings.xml的存放路径下的.ms/repository目录下。
注:此处所配置的路径要有足够的空间,否则将无法保存项目中检出的文件。
第三步:检查host文件配置
添加“ 192.168.0.240 ”到Host表配置中
eclipse中maven项目的配置
第一步:打开eclipse,选择window – preferences
第二步:选择Maven - User Settings,然后点击“Browse”选择settings.xml的存放路径
第三步:点击“update Settings”来更新工具文件的保存路径(会更新为“Maven项目配置前的准备”第二步中所配置的路径)
第四步:点击“OK”按钮完成属性的配置。
第五步:在eclipse中创建一个新的项目File - New - Other
第六步:选择maven项目,如图所示,点击“Next”按钮
第七步:选择要检出的项目类型和路径
也可以点击后面的“Browse”按钮选择已存在的路径
选择好需要的路径后点击“OK”按钮即可。
第十步:点击“Next”按钮
进入到如下所示的窗口,然后点击“Finish”即可:
Maven项目的导入
如果以上配置均完成则直接进入到maven项目的import界面,点击“Finish”按钮即可导入成功。
Maven项目的创建
右键->new->project…->maven->maven project->
勾选Create a simple project 其他默认->next->
Group Id:com.goldgov.demo(相同格式即可)
Artifact Id:selenium-dome(相同格式即可)
->finishi ,创建成功
导入jar包:双击pom.xml->选择Dependencies页签->add->
Group Id: org.seleniumhq.selenium
Artifact Id: selenium-remote-driver
或
Group Id: org.seleniumhq.selenium
Artifact Id: selenium-ie-driver(导入org.openqa.selenium.ie.InternetExplorerDriver)
或
Group Id: org.seleniumhq.selenium
Artifact Id: selenium-chrome-driver(导入org.openqa.selenium.chrome.ChromeDriver)
或
Group Id: org.seleniumhq.selenium
Artifact Id: selenium-Firefox-driver(导入org.openqa.selenium.firefoxe.FireFoxDriver)selenium与jenkins集成
(Hudsoan +Svn +Maven)+
(Manen +selenium)
=hudson+svn+tomcat+maven(集成了selenium的maven)
driver.switchTo().alert().getText().contains("请输入用户名")
((hasInputDevices)driver)getkeyboard().sendkeys(keys.arrow_down);
注意:
如果在一个java 文件中的@Test 比较多,那么需要注意@Before / @After 和@BeforeClass / @AfterClass 是不一样的,前者是每一个@Test 执行前后都会运行;后者只执行一次(详细请参考jUnit 的文档)。
远程测试:
System.setProperty("webdriver.ie.driver",
"D:/software/selenium/IEDriverServer_64.exe");
if (driver != null) {
return;
} else {
DesiredCapabilities ieCapabilities = DesiredCapabilities
.internetExplorer();
ieCapabilities
.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
driver = new RemoteWebDriver(new URL(
"http://192.168.0.249:4444/wd/hub"), ieCapabilities);
// driver = new InternetExplorerDriver(ieCapabilities);
}
baseUrl = "http://192.168.0.246:8080/orchid";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
long time = new Date().getTime();
DATACODE = String.valueOf(time);。