Selenium2.0 WebDriver入门指南
Selenium2.0 WebDriver入门指南
1.1 下载selenium2.0的lib包
http://code.google.com/p/selenium/downloads/list
官方User Guide:http://seleniumhq.org/docs/
1、MouseOver尝试
selenium.mouseOver(db.getElementXpath("tool_printerInfo_Image"));
MySelenium.CpaturePicture(selenium,browser, "90601002");
result.resultOfIsTrue(selenium.isTextPresent("HPENVY 120 series"));
assertTrue(result.isResult());
1.2 用webdriver打开一个浏览器
我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器。但是做页面的测试,速度通常很慢,严重影 响持续集成的速度,这个时候建议使用HtmlUnit,不过HtmlUnitDirver运行时是看不到界面的,对调试就不方便了。使用哪种浏览器,可以 做成配置项,根据需要灵活配置。
- 打开firefox浏览器:
//Create a newinstance of the Firefox driver
WebDriver driver = newFirefoxDriver();
- 打开IE浏览器
//Create a newinstance of the Internet Explorer driver
WebDriver driver = newInternetExplorerDriver ();
打开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 如何找到页面元素
Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找。
假设页面写成这样:
<input type="text"name="passwd"id="passwd-id" />
那么可以这样找到页面的元素:
通过id查找:
WebElement element =driver.findElement(By.id("passwd-id"));
或通过name查找:
WebElement element =driver.findElement(By.name("passwd"));
或通过xpath查找:
WebElement element=driver.findElement(By.xpath("//input[@id='passwd-id']"));
但页面的元素经常在找的时候因为出现得慢而找不到,建议是在查找的时候等一个时间间隔。
1.5 如何对页面元素进行操作
找到页面元素后,怎样对页面进行操作呢?我们可以根据不同的类型的元素来进行一一说明。
1.5.1输入框(text fieldor textarea)
找到输入框元素:
WebElement element =driver.findElement(By.id("passwd-id"));
在输入框中输入内容:
element.sendKeys(“test”);
将输入框清空:
element.clear();
获取输入框的文本内容:
element.getText();
1.5.2下拉选择框(Select)
找到下拉选择框的元素:
Select select = newSelect(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();
1.5.3单选项(Radio Button)
找到单选框元素:
WebElement bookMode=driver.findElement(By.id("BookMode"));
选择某个单选项:
bookMode.click();
清空某个单选项:
bookMode.clear();
判断某个单选项是否已经被选择:
bookMode.isSelected();
1.5.4多选项(checkbox)
多选项的操作和单选的差不多:
WebElement checkbox =driver.findElement(By.id("myCheckbox."));
checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();
1.5.5按钮(button)
找到按钮元素:
WebElement saveButton =driver.findElement(By.id("save"));
点击按钮:
saveButton.click();
判断按钮是否enable:
saveButton.isEnabled ();
1.5.6左右选择框
也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如:
Select lang = newSelect(driver.findElement(By.id("languages")));
lang.selectByVisibleText(“English”);
WebElement addLanguage=driver.findElement(By.id("addButton"));
addLanguage.click();
1.5.7弹出对话框(Popup dialogs)
Alert alert =driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
1.5.8表单(Form)
Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:
WebElement approve =driver.findElement(By.id("approve"));
approve.click();
或
approve.submit();//只适合于表单的提交
1.5.9上传文件
上传文件的元素操作:
WebElement adFileUpload=driver.findElement(By.id("WAP-upload"));
String filePath ="C:\test\\uploadfile\\media_ads\\test.jpg";
adFileUpload.sendKeys(filePath);
1.6 Windows和 Frames之间的切换
一般来说,登录后建议是先:
driver.switchTo().defaultContent();
切换到某个frame:
driver.switchTo().frame("leftFrame");
从一个frame切换到另一个frame:
driver.switchTo().frame("mainFrame");
切换到某个window:
driver.switchTo().window("windowName");
1.7 调用Java Script
Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:
JavascriptExecutor js =(JavascriptExecutor) driver;
js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+inventoryId + "','" + fieldName + "','"
+ value + "');})()");
1.8 页面等待
页面的操作比较慢,通常需要等待一段时间,页面元素才出现,但webdriver没有提供现成的方法,需要自己写。
等一段时间再对页面元素进行操作:
public voidwaitForPageToLoad(longtime) {
try {
Thread.sleep(time);
} catch (Exceptione) {
}
}
在找WebElement的时候等待:
publicWebElementwaitFindElement(By by) {
returnwaitFindElement(by, Long.parseLong(CommonConstant.GUI_FIND_ELEMENT_TIMEOUT),Long
.parseLong(CommonConstant.GUI_FIND_ELEMENT_INTERVAL));
}
publicWebElementwaitFindElement(By by, long timeout, long interval) {
long start = System.currentTimeMillis();
while (true) {
try {
return driver.findElement(by);
} catch(NoSuchElementException nse) {
if (System.currentTimeMillis()- start >= timeout) {
throw newError("Timeout reached and element[" + by + "]notfound");
} else {
try {
synchronized(this) {
wait(interval);
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
1.9 在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 WebDriverimplementation. Firefox is used hereas an example
WebDriver driver = newFirefoxDriver();
// A "base url", used byselenium to resolve relativeURLs
String baseUrl="http://www.google.com";
// Create the Seleniumimplementation
Selenium selenium = newWebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q","cheese");
selenium.click("name=btnG");
// Get the underlying WebDriverimplementation back. This willrefer to the
// same WebDriver instance as the"driver" variableabove.
WebDriver driverInstance =((WebDriverBackedSelenium)selenium).getUnderlyingWebDriver();
//Finally, closethebrowser. Call stop on the WebDriverBackedSelenium instance
//instead ofcallingdriver.quit(). Otherwise, the JVM will continue running after
//the browser hasbeenclosed.
selenium.stop();
我分别使用WebDriver API和SeleniumRC API写了一个Login的脚本,很明显,后者的操作更加简单明了。
WebDriver API写的Login脚本:
public voidlogin() {
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 voidlogin() {
selenium.selectFrame("relative=top");
selenium.selectFrame("mainFrame");
selenium.type("username","manager@ericsson.com");
selenium.type("password","manager");
selenium.click("loginButton");
}
右键点击:
Actions action = new Actions(driver); action.contextClick(driver.findElement(By.xpath("/html/body/div/div[2]/div[2]/div/div/div/div/div/div/div[2]/ul/li/ul/li[2]/ul/li/ul/li[5]/div/a/span"))).perform();
元素移动
Actions builder = newActions(driver); builder.moveToElement(driver.findElement(By.xpath("/html/body/div[6]/div/div/form/div[3]/div[2]/div/div/div/div[2]/div/table/tbody/tr/td/table/tbody/tr/td[3]/table/tbody/tr[2]/td[2]/em/button"))).perform();
元素双击
builder.doubleClick(onElement)
WebDriver实现窗体的最大化
最优方法:driver.manage().window().maximize();
@Test
@Parameters( { "webSite" })
publicvoid setUp_ChromeDriver(String webSite) throws Exception {
//.\\lib\\IEDriverServer.exe 是lib目录下的驱动
System.setProperty("webdriver.chrome.driver","./lib/chromedriver.exe");
driver = new ChromeDriver();
maximise(driver);
Thread.sleep(2000);
baseUrl = webSite;
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
script(driver);
}
//使窗口最大化函数,通过检测显示器的宽和高来实现
publicstaticvoid maximise(WebDriver driver) {
final JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.open('','testwindow','width=400,height=200')");
driver.close();
driver.switchTo().window("testwindow");
js.executeScript("window.moveTo(0,0);");
/*1280和1024分别为窗口的宽和高,可以用下面的代码得到
screenDims = Toolkit.getDefaultToolkit().getScreenSize();
width = (int)screenDims.getWidth();
height = (int)screenDims.getHeight(); */
js.executeScript("window.resizeTo(1440,900);");
System.out.println(Toolkit.getDefaultToolkit().getScreenSize().getWidth());
System.out.println(Toolkit.getDefaultToolkit().getScreenSize().getHeight());
}
Selenium2.0 WebDriver入门指南相关推荐
- TensorFlow 2.0 快速入门指南 | iBooker·ApacheCN
原文:TensorFlow 2.0 Quick Start Guide 协议:CC BY-NC-SA 4.0 自豪地采用谷歌翻译 不要担心自己的形象,只关心如何实现目标.--<原则>,生活 ...
- selenium2.0(WebDriver) API - 转载自:http://www.cnblogs.com/puresoul/p/3477918.html
1.1 下载selenium2.0的包 官方download包地址:http://code.google.com/p/selenium/downloads/list 官方User Guide: h ...
- helm v3.8.0 命令入门指南
文章目录 1. 条件 2. 安装 2.1 二进制版本安装 2.2 脚本安装 2.3 更多安装方式 3. 三大概念 4. 常用方法 4.1 'helm repo':使用存储库 4.2 'helm sea ...
- Selenium2.0 WebDriver功能测试入门(Java版)
我也一直使用着原始的人工测试手段,随着内容的不断增多,测试起来就越发的繁杂,而且经常犯懒,这样就会忽略很多本该发现的问题,而且也容易出现旧的bug 反复出现的情况,这都是测试不规范造成的.要做好东西就 ...
- 【LayaAir2.0】LayaAir2.0新手入门指南(目录)
第一章 全部课程介绍 1.1 大纲简介 1.2.课程目标 1.2.1 了解产业机会与Layabox的产品 1.2.2 认识LayaAir引擎的结构 1.2.3 真正掌握IDE的使用 场景 UI ...
- WeUI 简明入门指南
由于 WeUI 0.4.x 到 1.x 版本更新改动较大,所以本文仅适用于 0.4.x 版本,适用于 1.x 版本的入门指南请查看 WeUI 1.0 简明入门指南. 之前做智慧校园的时候想找一个开源的 ...
- 网关协议——OpenID Connect(身份认证+OAuth2授权)入门指南
OpenID Connect 如果要谈单点登录和身份认证,就不得不谈OpenID Connect (OIDC).最典型的使用实例就是使用Google账户登录其他应用,这一经典的协议模式,为其他厂商的第 ...
- gridcontrol值为0时设置为空_XASSET 4.0入门指南
XASSET 5.1已经发布 XASSET 5.1为Unity项目提供了可以快速投入到生产环境中使用的具有更智能和灵活的资源分包.热更新机制和稳健高效的资源加载和内存管理的资源管理方案.它不仅可以服务 ...
- Asp.net MVC3.0 入门指南 6 审视编辑方法和视图
审视编辑方法和视图 在这一节中,您将审视movie控制器生成的响应方法和视图.然后您将添加 一个自定义搜索页面. 运行程序并通过在URL追加/Moives浏览movie控制器.把鼠标悬停在Edit 链 ...
最新文章
- animate用法 js原生_用 原生Javascript 创建带动画的固顶导航菜单
- 网络缓存 峰值 linux,Linux Page Cache调优在Kafka中的应用
- Python编程基础:第四十节 类变量Class Variables
- python3根据地址批量获取百度地图经纬度
- JavaWeb中如何通过Request对象获取客户端IP地址
- 30分钟回顾AI数学基础知识(一)
- 【小白学习C++ 教程】十五、C++ 中的template模板和泛型
- html 首行缩进2个汉字
- ASP.NET教程11
- yytextview多种格式_iOS YYText的使用笔记一(YYTextView图文编辑器)
- JAVA-WEB开发环境和搭建
- resultJP在Java中_java result是如何直接变为对象的
- VB利用资源文件进行工作
- 游戏开发中的脚本语言
- 城市土地利用分布数据/城市功能区划分布数据/城市poi感兴趣点/植被类型分布
- 台式机主板常见接口资料
- Linux下使用rm删除文件,并排除指定文件(亲测可行)
- bitcoin rpc command
- 怎么安装iso服务器系统安装win7系统,win7纯净版iso怎么安装
- 求函数最值(模拟退火算法C++实现)