java +Selenium 2 环境搭建
java +Selenium 2 入门学习
Selenium 2介绍
Selenium 是用于测试 Web 应用程序用户界面 (UI) 的常用框架。它是一款用于运行端到端功能测试的超强工具。您可以使用多个编程语言编写测试,并且 Selenium 能够在一个或多个浏览器中执行这些测试。
Selenium(以下简称为 Selenium 1)并不是能够在浏览器中自动化功能测试的惟一工具。由 Simon Stewart(来自 Google)创建的 WebDriver 是一个具有类似目标的项目。要控制浏览器,需要依赖采用本机支持的独立客户端。WebDriver 仅提供 Java 绑定,并不能支持 Selenium 1 所能支持的那么多浏览器。
- Selenium 1 + WebDriver = Selenium 2
Selenium 1 和 WebDriver 合并成一款性能更佳的产品 Selenium 2(或 Selenium WebDriver),该款产品发行于 2011 年。Selenium 2 具有来自 WebDriver 的清晰面向对象 API,并能以最佳的方式与浏览器进行交互。Selenium 2 不使用 JavaScript 沙盒,它支持多种浏览器和多语言绑定。在撰写本文时,Selenium 2 为下列程序提供驱动程序:
- Mozilla Firefox
- Google Chrome
- Microsoft Internet Explorer
- Opera
- Apple iPhone
- Android browsers
借 助 Selenium 2,您可使用 Java、C#、Ruby、和 Python 编写测试。Selenium 2 还提供基于 HtmlUnit 的无外设驱动,是用于测试 Web 应用程序的 Java 框架。HtmlUnit 运行速度特别快,但它不是一个真正与真实浏览器相关联的驱动。
Selenium 2环境搭建及安装
selenium2(WebDriver)环境搭建
- 下载并安装Java
- 下载并配置Eclipse
- 配置Firebug和FirePath
- 配置Selenium RC
配置Selenium的webdriver
1、安装jdk并配置环境变量:
- jdk安装jdk下载地址:
http://www.oracle.com/technetwork/java/javase/downloads/index.html环境变量配置,如:CLASSPATH=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jarJAVA_HOME=D:\Program Files\Java\jdk1.6.0_10PATH=%JAVA_HOME%\bin
2、安装Firefox,Selenium IDE,Firebug和xpahter
安装FireFox
Firefox版本有一定限制,需要和selenium IDE相匹配。下载地址: http://www.firefox.com.cn/download/
安装Selenium IDE
Selenium IDE是基于FIREFOX浏览器的一个插件,提供GUI界面来运行Selenium测试。Selenium IDE提供脚本录制和回放功能,可以将用户在浏览器中执行的操作记录下来,生成各种形式的脚本,可以将这些脚本保存供selenium使用。Selenium IDE主要是用在Selenium 1.0中,在Selenium 2.0中基本不使用。
1)下载Selenim IDE下载地址:http://seleniumhq.org/projects/ide/
2)安装:直接把下载的Selenium IDE文件拖到FireFox浏览器窗口中,按提示操作即可安装成功。
安装Firebug
1)打开Firefox浏览器
2)点击菜单“工具(T)”,下拉列表中选择“附加组件”。
3)“获取附加组件”
4)在搜索里输入“firebug”,稍等即可。
5)点击“添加至Firefox”
6)OK,重启浏览器即可。
安装xpahter
1)打开Firefox浏览器
2)点击菜单“工具(T)”,下拉列表中选择“附加组件”。
3)“获取附加组件”
4)在搜索里输入“xpahter”,稍等即可。
5)点击“添加至Firefox”
6)OK,重启浏览器即可。
安装xpath checker
1)打开Firefox浏览器
2)点击菜单“工具(T)”,下拉列表中选择“附加组件”。
3)“获取附加组件”
4)在搜索里输入“xpath checker”,稍等即可。
5)点击“添加至Firefox”
6)OK,重启浏览器即可。
3、安装eclipse
安装eclipse
Eclipse:Version: Kepler Service Release 1,下载地址:http://www.eclipse.org/downloads/
4、安装selenium webdriver
1)下载地址: http://code.google.com/p/selenium/downloads/list
官方UserGuide:http://seleniumhq.org/docs/
2)下载:selenium-server-standalone-2.44.0.jar和selenium-java-2.44.0.zip(使用java语言的下载该包)。
3)解压下载的selenium-java-2.44.0.zip文件,这个包里面包含四部分,如下图:
Selenium 使用
Demo 1:java+firefox+selenium+eclipse
Step1:
新建一个Java Project,并把selenium-java解压后的文件copy到新建的project目录下
在Eclipse里新建一个project,然后引用selenium-java-2.44.0.zip解压出来的文件拷到新建的project目录下,目录结构如下图:
Step 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
添加完之后目录结构如下图,多了Referenced Libraries,这里就是上面那一步添加进去的jar包:
Step 3:关联webdriver的源码
Step 4:在src下面新建测试类,如下图
代码如下,主要是打开百度,然后在搜索框输入glen,点击搜索按钮,关闭浏览器。
package com.selenium.Glen;
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.*;public class TestHelloWorld {public static void main(String[] args) { //如果火狐浏览器没有默认安装在C盘,需要制定其路径//System.setProperty("webdriver.firefox.bin", "D:/Program Files/Mozilla firefox/firefox.exe"); WebDriver driver = new FirefoxDriver();driver.get("http://www.baidu.com/");driver.manage().window().maximize();WebElement txtbox = driver.findElement(By.name("wd"));txtbox.sendKeys("Glen");WebElement btn = driver.findElement(By.id("su"));btn.click();driver.close(); } }
然后直接右键–>Run As–>Java Application就可以看到效果了。
Demo 2:java+firefox+selenium+eclipse+TestNG
打印输出
System.out.println(“start firefox browser…”);
Chrome浏览器
http://blog.csdn.net/robinlovesnow/article/details/6599612
Step1:安装chromedriver到chrome安装目录下
Step2.将chromedriver添加到工程里
Step3.设置浏览器路径
Chrome浏览器
System.setProperty(“webdriver.chrome.driver”, “C:/Users/Administrator/AppData/Local/Google/Chrome/Application/chromedriver.exe”);
WebDriver driver = new ChromeDriver();
IE浏览器
System.setProperty(“webdriver.ie.driver”, IEDriver);
driver = new InternetExplorerDriver();
Firefox浏览器
System.setProperty(“webdriver.firefox.bin”, “E:/Program Files/Mozilla firefox/firefox.exe”);
WebDriver driver = new FirefoxDriver();
疑问解决
Question 1:selenium 火狐浏览器测试失败提示:
org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
提示这个错误,说明selenium的版本和firefox不兼容了,需要升级selenium
Question2:提示Only local connections are allowed.
通过Selenium IDE 录制脚本
3、通过Selenium IDE 录制脚本
{ 点这里就开始录制!}
以上操作是:百度输入hao123,点击搜索。
4、录制完毕导出selenium-java脚本
模板:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class OpenTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //设置浏览器driver System.setProperty("webdriver.firefox.bin", "E:/Program Files/Mozilla firefox/firefox.exe");WebDriver driver; driver=new FirefoxDriver(); //打开百度的首页 driver.get("http://www.baidu.com"); driver.findElement(By.linkText("hao123")).click(); //关闭浏览器 //driver.close(); }
}
5、启动不同浏览器
Firefox:
System.setProperty("webdriver.firefox.bin", "E:/Program Files/Mozilla firefox/firefox.exe");
IE:
System.setProperty(“webdriver.ie.driver”, “C:/liuluanqi/IEDriverServer.exe”); 这个应该也可以 试试
//Create a newinstance of the Internet Explorer driverWebDriver driver = newInternetExplorerDriver ();or//path to ur IEDriver exe public static String IEDriver_64 = “C:/IEDriverServer.exe”;
System.setProperty(“webdriver.ie.driver”, IEDriver);
driver = new InternetExplorerDriver();
Chrome:
System.setProperty(“webdriver.chrome.driver”, bsPath);WebDriverdriver = new ChromeDriver();
or//location of your chrome driver exe public static String ChromeDriver = “C:/selenium/gtn_fht/lib/chromedriver.exe”;
System.setProperty(“webdriver.chrome.driver”, ChromeDriver);
// driver.manage().window().maximize() for Chrome driver throws // org.openqa.selenium.WebDriverException: Maximize automation interface is not supported for this version of Chrome. // so using the below capabilities
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(“chrome.switches”, Arrays.asList(“–start-maximized”));
driver = new org.openqa.selenium.chrome.ChromeDriver(capabilities);
6、元素操作
查找元素
使用操作如何找到页面元素Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找。下面介绍几种比较常用的方法。
By ID假设页面写成这样:
那么可以这样找到页面的元素:
通过id查找:
WebElement element = driver.findElement(By.id(“user”));
By Name或通过name查找:
WebElement element = driver.findElement(By.name(“userName”));
By XPATH或通过xpath查找:
WebElement element =driver.findElement(By.xpath(“//input[@id=‘user’]“));By Class Name假设页面写成这样:
By Link Text假设页面元素写成这样:baidu>那么可以通过这样查找:
WebElement baidu=driver.findElement(By.linkText(“baidu”));
输入框传值
输入框(text field or textarea) 找到输入框元素:
WebElement element = driver.findElement(By.id(“passwd-id”));
在输入框中输入内容:
element.sendKeys(“test”);
将输入框清空:
element.clear();
获取输入框的文本内容:
element.getText();
下拉菜单
下拉选择框(Select)找到下拉选择框的元素:
Select select = new Select(driver.findElement(By.id(“select”)));
选择对应的选择项:select.selectByVisibleText(“testName”);
或
select.selectByValue(“name”);
不选择对应的选择项:
select.deselectAll();
select.deselectByValue(“name”);
select.deselectByVisibleText(“姓名”);
或者获取选择项的值:
select.getAllSelectedOptions();
select.getFirstSelectedOption();
单选框
单选项(Radio Button)找到单选框元素:
WebElement sex=driver.findElement(By.id(“sex”));
选择某个单选项:
sex.click();
清空某个单选项:
sex.clear();
判断某个单选项是否已经被选择:
sex.isSelected();
复选框
多选项(checkbox)多选项的操作和单选的差不多:
WebElement area =driver.findElement(By.id(“area .”));
area .click();
area .clear();
area .isSelected();
area .isEnabled();
按钮
按钮(button)找到按钮元素:
WebElement saveButton = driver.findElement(By.id(“save”));
点击按钮:
saveButton.click();
判断按钮是否enable:
saveButton.isEnabled ();
左右选择框也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如:
Select name= new Select(driver.findElement(By.id(“name”)));
name.selectByVisibleText(“hellen”);
WebElement addName=driver.findElement(By.id(“addButton”));
addName.click();
弹出框
弹出对话框(Popup dialogs)Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
表单提交
表单(Form)Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:
WebElement sub= driver.findElement(By.id(“sub”));
sub.click();
或
sub.submit();//只适合于表单的提交
上传附件
上传文件 (Upload File)上传文件的元素操作:
WebElement picFile = driver.findElement(By.id(“picFile ”));
String filePath = “d:\report\600x600x0.jpg”;
picFile .sendKeys(filePath);
多窗口切换
Windows 或 Frames之间的切换
首先切换到默认的frame
driver.switchTo().defaultContent();
切换到某个frame:
driver.switchTo().frame(“leftFrame”);
从一个frame切换到另一个frame:
driver.switchTo().frame(“mainFrame”);
切换到某个window:
driver.switchTo().window(“windowName”);
导航
导航 (Navigationand History)打开一个新的页面:
driver.navigate().to(“http://www.baidu.com”);
通过历史导航返回原页面:
driver.navigate().forward();
driver.navigate().back();
IWebDriver.SwitchTo().Frame(IWebElement frame)
如果一个页面是一个html元素, 只有一个head, 一个body, 那么使用IWebDriver.FindElement()查找页面中的任何一个元素都没有问题。但是,由于页面中<frame … 的使用,使得一个原始的html页面中可以包含多个子html页面, 在这种情况下,使用IWebDrivr.FindElement()查找页面 某个元素,如果元素是属于元素大的html的, 那么没有问题。若该元素是属于某个子的<frame …下的,获得页面元素会失败的。要想成功,首先要弄清楚该元素所属的frame的, 其次, 将IWebDriver切换到该frame, 然后再使用IWebDriver.FindElement()查找这个元素。
- 获得页面元素所属于的frame, 拿到它的name属性。
- 使用IWebDriver.FindElements()获得本页面中所有的frame, 使用ByTagName。
- 循环遍历所有Frame,查找name属性相符的Frame。
- 将IWebDriver焦点切换到该Frame, 查找要获得的页面元素。
例如, 我的页面元素如下:
这个页面中, 要想获得id是"testcategory"的span元素, 直接使用IWebDriver.FindElement(By.ID(“testcategory”))是没有用的, 找不到这个element。
正确的代码如下:
using Se = OpenQA.Selenium;using SIE = OpenQA.Selenium.IE;SIE.InternetExplorerDriver driver = new SIE.InternetExplorerDriver();// all framesIList<Se.IWebElement> frames = driver.FindElements(Se.By.TagName("frame"));Se.IWebElement controlPanelFrame = null;foreach (var frame in frames){if (frame.GetAttribute("name") == "ControlPanelFrame"){controlPanelFrame = frame;break;}}if (controlPanelFrame != null){driver.SwitchTo().Frame(controlPanelFrame);} // find the spane by id in frame "ControlPanelFrame"Se.IWebElement spanElement = driver.FindElement(Se.By.Id("testcategory"));
IWebDriver.SwitchTo().Window(string windowName)
在页面上点击一个button, 然后打开了一个新的window, 将当前IWebDriver的focus切换到新window,使用IWebDriver.SwitchTo().Window(string windowName)。
例如, 我点击按钮以后弹出一个名字叫做"Content Display"的window, 要切换焦点到新窗口的方法是, 首先,获得新window的window name, 大家不要误以为page tile就是window name 哦, 如果你使用driver.SwitchTo().Window(“Content Display”)是找不到window name 叫做"Content Display"的窗口的, 其实Window Name 是一长串数字,类似“59790103-4e06-4433-97a9-b6e519a84fd0”。
要正确切换到"Content Display"的方法是:
- 获得当前所有的WindowHandles。
- 循环遍历到所有的window, 查找window.title与"Content Display"相符的window返回。
大家明白了吧, 正确的代码:
using Se = OpenQA.Selenium;using SIE = OpenQA.Selenium.IE;public static string GoToWindow(string title, ref SIE.InternetExplorerDriver driver){driver.SwitchTo().DefaultContent();// get all window handlesIList<string> handlers = driver.WindowHandles;foreach (var winHandler in handlers){driver.SwitchTo().Window(winHandler);if (driver.Title == title){return "Success";}else{driver.SwitchTo().DefaultContent();}}return "Window Not Found";}
配置变量文件
代码
窗口最大化:
driver.manage().window().maximize();
等待
Thread.sleep(500);
截屏
import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;public class screenshot {public static void snapshot(TakesScreenshot drivername, String filename){// this method will take screen shot ,require two parameters ,one is driver name, another is file nameFile scrFile = drivername.getScreenshotAs(OutputType.FILE);// Now you can do whatever you need to do with it, for example copy somewheretry {System.out.println("save snapshot path is:E:/"+filename);FileUtils.copyFile(scrFile, new File("D:/screen/"+filename));} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println("Can't save screenshot");e.printStackTrace();} finally{System.out.println("screen shot finished");}}
}
断言
ExpectedConditions & Assert
boolean isPass= ExpectedConditions.textToBePresentInElement(driver.findElement(By.linkText(“简历”)), “简历”).apply(driver);
if(!isPass){
Assert.fail(“校验失败!”);
}
获取各种值
driver.getTitle() //获取页面标题
element.getAttribute(“name”) //获取对象各种属性
element.getText() //获取对象的文本
java +Selenium 2 环境搭建相关推荐
- 《手把手教你》系列基础篇之(一)-java+ selenium自动化测试-环境搭建(上)(详细教程)
1.简介 jmeter系列的文章结束,本来想趁热打铁顺别将Jmeter和接口测试介绍一下,但是感觉Jmeter时间太长了怕大家吃腻了,还有一个原因就是许多小伙伴们或者童鞋们私信问宏哥什么时候可以有ja ...
- java selenium (二) 环境搭建方法一
webdriver 就是selenium 2. webdriver 是一款优秀的,开源的,自动化测试框架. 支持很多语言. 本文描述的是用java Eclipse 如何搭建环境 阅读目录 首先 ...
- 测试小白基于java的selenium自动化测试环境搭建
本人是一个软件测试小白,自己在研究自动化测试时,真的入了不少坑,直到现在,才勉强将环境搭建了起来. 在此,我随随便便总结了一下基于java的selenium自动化测试环境搭建,送给正在学习软件测试的你 ...
- selenium Grid2环境搭建和基本使用
Selenium Grid简介 利用Selenium Grid可以使主节点(hub)的测试用例在不同主机即分支点(node)运行.可以使一份测试用例在不同环境下(操作系统.浏览器)执行自动化测试.Se ...
- 从零开始编写Web自动化测试脚本(一)--Selenium+WebDriver环境搭建
第一章 Selenium+WebDriver环境搭建 第二章 Selenium定位方式 第三章 元素常用属性 第四章 自动化中的三种等待 第五章 自动化浏览器设置及句柄.窗口切换操作 第六章 鼠标.键 ...
- JAVA JDK windows环境搭建
JAVA JDK windows环境搭建 系统环境: windows 10 , JDK 1.7 操作步骤: 1.下载JDK,全部选择默认,直接点击下一步 2.配置环境变量 打开环境变量 变量设置 JA ...
- selenium自动化测试环境搭建及启动safair浏览器(Mac)
selenium自动化测试环境搭建及启动safair浏览器 ###前提环境 mac系统 safair浏览器 python(只不过mac自带python2.7可以不用下载) pycharm 打开终端 p ...
- Groovy 和 Java 联合开发环境搭建
Groovy 和 Java 联合开发环境搭建 1. 在主 pom 的 properties 中加上 <groovy.version>2.5.2</groovy.version> ...
- Java从入门到实战总结-1.1、Java基础之环境搭建和eclipse安装
Java从入门到实战总结-1.1.Java基础之环境搭建和eclipse安装 文章目录 Java从入门到实战总结-1.1.Java基础之环境搭建和eclipse安装 1.Hello Java 1.1. ...
最新文章
- RSA签名的PSS模式
- AQS独占式获取同步状态和释放同步状态(源码阅读笔记)
- 阿里云西安ACE同城会 | 钉钉生态应用促进企业信息化实战沙龙
- 2019年第十届蓝桥杯 - 省赛 - C/C++大学C组 - D. 质数
- 一个DataTable赋值给另一个
- AUTOSAR从入门到精通100讲(四十一)-基于AUTOSAR与Matlab开发应用层三部曲-应用层总体功能开发和集成
- c#扩展方法奇思妙用高级篇八:Type类扩展
- tts文字转语音_Android文字转语音(TTS)
- Dungeon Master 地下城大师(BFS进阶)
- 计算机体系结构现状及发展论文,计算机体系结构的发展及技术问题探讨
- 美国专利客体适格性判断标准浅析
- 程序员学金融-金融科普(4)-净资产收益率
- 5316. 竖直打印单词(print-words-vertically)
- 最全的阿里面试经验(一)
- beyond compare 过期解决方法
- 林轩田机器学习基石笔记(第23-24节)——上限函数Bounding Function
- aes相关资料整理及代码C/C++
- 32位系统装8g内存条?能用吗
- 浅析功耗性能肖特基二极管的重要性
- Infragistsitcs NetAdvantage WebCombo 控件
热门文章
- C51接入OneNET-实现数据上传和命令下发
- 晶振01——晶振分类和无源晶振的设计
- 第一数字定律识别数据作假
- 观看《创新的力量》观后感
- bootstrap页面sidebar
- python随机抽签列表中的同学值日_神奇的大抽签--Python中的列表,中国大学MOOC(慕课)答案公众号搜题...
- 为树莓派打实时preempt_rt补丁
- el-checkbox的坑(点击全选状态改变了但是不生效)
- Java程序员如何不断提高自己的专业技能
- python爬虫:批量抓取代理ip,进行验证,抓取豆瓣网站影视信息