Selenium Web 自动化 - Selenium常用API

2016-08-01

目录

1 对浏览器操作
  1.1 用webdriver打开一个浏览器
  1.2 最大化浏览器&关闭浏览器
  1.3 设置浏览器窗口大小
  1.4 打开测试页面
  1.5 处理浏览器弹出的新窗口
2 页面元素定位
3 如何对页面元素进行操作
  3.1 WebElement相关方法
  3.2 iFrame的处理
  3.3 输入框(text field or textarea)
  3.4 下拉选择框(Select)
  3.5 单选项(Radio Button)
  3.6 多选项(checkbox)
  3.7 按钮(button)
  3.8 处理Alert
  3.9 上传文件
    3.9.1 元素标签是Input时上传方式
    3.9.2 通过操作桌面浏览窗口上传
  3.10 Selenium处理HTML5
    3.10.1 处理Vedio
    3.10.2 处理Canvas
  3.11 表单(Form)
4 其他
  4.1 等待元素加载
  4.2 执行JS脚本
  4.3 模拟键盘操作

1 对浏览器操作


返回

1.1 用webdriver打开一个浏览器

//打开firefox浏览器:
WebDriver driver = new FirefoxDriver();
//打开IE浏览器
WebDriver driver = new InternetExplorerDriver ();
//打开HtmlUnit浏览器
WebDriverdriver = new HtmlUnitDriver();
//打开chrome浏览器
WebDriverdriver = new ChromeDriver();

1.2 最大化浏览器&关闭浏览器

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.close();
driver.quit();

1.3 设置浏览器窗口大小

    private static void SetWindowTest(WebDriver driver)
throws InterruptedException {
// 设置窗口的 宽度为:800,高度为600
Dimension d = new Dimension(800, 600);
driver.manage().window().setSize(d);
Thread.sleep(2000); // 设置窗口最大化
driver.manage().window().maximize();
Thread.sleep(2000); // 设置窗口出现在屏幕上的坐标
Point p = new Point(500, 300);
// 执行设置
driver.manage().window().setPosition(p);
Thread.sleep(2000);
}

1.4 打开测试页面

打开测试页面
driver.get("http://www.baidu.com/");
driver.navigate().to("http://www.baidu.com/");
//navigate方法会产生1个Navigator对象,其封装了与导航相关的一些方法,比如前进后退等

1.5 处理浏览器弹出的新窗口

    private static void MutiWindowTest(WebDriver driver)
throws InterruptedException {
WebDriver newWindow = null ;
driver.get("http://www.hao123.com/");
//浏览器最大化
driver.manage().window().maximize();
//获取当前页面句柄
String current_handles = driver.getWindowHandle();
//点击 百度链接
driver.findElement(By.xpath("//*[@data-title='百度']")).click();
//接下来会有新的窗口打开,获取所有窗口句柄
Set<String> all_handles = driver.getWindowHandles();
//循环判断,把当前句柄从所有句柄中移除,剩下的就是你想要的新窗口
Iterator<String> it = all_handles.iterator();
while(it.hasNext()){
if(current_handles == it.next()) continue;
//跳入新窗口,并获得新窗口的driver - newWindow
newWindow = driver.switchTo().window(it.next());
}
//接下来在新页面进行操作,也就是百度首页,我们输入一个java关键字进行搜索
Thread.sleep(5000);
WebElement baidu_keyowrd = newWindow.findElement(By.id("kw"));
baidu_keyowrd.sendKeys("java");
Thread.sleep(1000);
//关闭当前窗口,主要使用close而不是quite,
newWindow.close();
driver.switchTo().window(current_handles);
System.out.println(driver.getCurrentUrl());
}

2 页面元素定位


返回

Webdriver提供下面两种方法来定位页面元素,参数是By对像,最常用是By.id和By.name查找。

  • findElement   定位某个元素,如果没有找到元素会抛出异常:NoSuchElementException
  • findElements     定位一组元素

例如需要定位如下元素:

  <input class="input_class" type="text" name="passwd" id="passwd-id" /> 
//By.id
WebElement element = driver.findElement(By.id("passwd-id"));
//By.name
WebElement element = driver.findElement(By.name("passwd"));
//By.xpath
WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));
//By.className
WebElement element = driver.findElement(By.className("input_class"));
//By.cssSelector
WebElement element = driver.findElement(By.cssSelector(".input_class"));
//By.linkText
//通俗点就是精确查询
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
WebElement element = driver.findElement(By.linkText("百科"));
//By.partialLinkText:
//这个方法就是模糊查询
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
WebElement element = driver.findElement(By.partialLinkText("hao"));
//By.tagName
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
String test= driver.findElement(By.tagName("form")).getAttribute("name");
System.out.println(test);

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


返回

3.1 WebElement相关方法

Method   Summary
void clear() If   this element is a text entry element, this will clear the value.
void click() Click   this element.
WebElement findElement(By by) Find   the first WebElement  using the given method.
 java.util.List<WebElement> findElement(By   by) Find   all elements within the current context using the given mechanism.
 java.lang.String getAttribute(java.lang.String   name) Get   the value of a the given attribute of the element.
 java.lang.String getCssValue(java.lang.String.propertyName) Get   the value of a given CSS property.
Point GetLocation() Where   on the page is the top left-hand corner of the rendered element?
 Dimension getSize() What   is the width and height of the rendered element?
 java.lang.String getTagName()  Get   the tag name of this element.
 java.lang.String getText()  Get   the visible (i.e. not hidden by CSS) innerText of this element, including
sub-elements, without any leading or trailing whitespace.
 boolean isDisplayed() Is   this element displayed or not? This method avoids the problem of having to   parse an element's "style" attribute.
 boolean isEnabled() Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
 boolean isSelected() Determine   whether or not this element is selected or not.
 void sendKeys(java.lang.CharSequence...   keysToSend) Use   this method to simulate typing into an element, which may set its value.
 void submit() If   this current element is a form, or an element within a form, then this will   be submitted to the remote server.

3.2 iFrame的处理

driver.switchTo().frame(“city_set_ifr”); //传入的是iframe的ID
dr.switchTo().defaultContent(); //如果要返回到以前的默认content

3.3 输入框(text field or textarea)

WebElement element = driver.findElement(By.id("passwd-id"));
element.sendKeys(“test”);//在输入框中输入内容:
element.clear();     //将输入框清空
element.getText();   //获取输入框的文本内容:

3.4 下拉选择框(Select)

Select select = new Select(driver.findElement(By.id("select")));
select.selectByVisibleText(“A”);
select.selectByValue(“1”);
select.deselectAll();
select.deselectByValue(“1”);
select.deselectByVisibleText(“A”);
select.getAllSelectedOptions();
select.getFirstSelectedOption();

示例:

package seleniumAPIDemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select; public class SelectDemo { public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
iframeAndSelectTest(driver);
driver.quit();
} private static void iframeAndSelectTest(WebDriver driver)
throws InterruptedException {
driver.get("http://www.2345.com/"); //浏览器最大化
driver.manage().window().maximize();
//点击切换按钮
driver.findElement(By.id("J_city_switch")).click();
//进入天气城市选择iframe
driver.switchTo().frame("city_set_ifr");
Thread.sleep(2000); //然后在进行选择城市
//定位 省下拉框
Select province = new Select(driver.findElement(By.id("province")));
province.selectByValue("20");
Thread.sleep(2000); //定位 城市下拉框
Select city = new Select(driver.findElement(By.id("chengs")));
city.selectByIndex(0);
Thread.sleep(2000); //定位区
Select region = new Select(driver.findElement(By.id("cityqx")));
region.selectByVisibleText("X 新密");
Thread.sleep(2000); //点击定制按钮
driver.findElement(By.id("buttonsdm")).click();
Thread.sleep(2000);
//返回默认的content
driver.switchTo().defaultContent();
}
}

3.5 单选项(Radio Button)

WebElement radio=driver.findElement(By.id("BookMode"));
radio.click();     //选择某个单选项
radio.clear();     //清空某个单选项
radio.isSelected();  //判断某个单选项是否已经被选择

3.6 多选项(checkbox)

WebElement checkbox = driver.findElement(By.id("myCheckbox."));
checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();

3.7 按钮(button)

WebElement btn= driver.findElement(By.id("save"));
btn.click();      //点击按钮
btn.isEnabled ();  //判断按钮是否enable

3.8 处理Alert

弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();
alert.accept();  //确定
alert.dismiss();  //取消
alert.getText(); //获取文本

示例:

    private static void alertTest(WebDriver driver) throws InterruptedException {

        driver.get("http://www.w3school.com.cn/tiy/t.asp?f=hdom_alert");
//浏览器最大化
driver.manage().window().maximize();
//进入frame
driver.switchTo().frame("i");
//找到按钮并点击按钮
driver.findElement(By.xpath("//*[@value='显示消息框']")).click();
Thread.sleep(2000);
//获取Alert
Alert a = driver.switchTo().alert();
//打印出文本内容
System.out.println(a.getText());
//点击确定
Thread.sleep(2000); a.accept();
// 如果alert上有取消按钮,可以使用a.dismiss()代码
}

3.9 上传文件

3.9.1 元素标签是Input时上传方式

Upload.html文件内容如下:

<body>
<input type="file" id="fileControl" value="选择文件"/>
</body>

代码如下:

    private static void uploadTest1(WebDriver driver) throws InterruptedException {
//打开上传的网页 - get中输入upload的地址
driver.get("D:\\DownLoad\\UploadTest\\upload.html");
WebElement e1 = driver.findElement(By.id("fileControl"));
Thread.sleep(2000);
//输入要上传文件的地址
e1.sendKeys("D:\\DownLoad\\UploadTest\\被上传的文件.txt");
Thread.sleep(2000);
}

3.9.2 通过操作桌面浏览窗口上传

示例2 上传文件

3.10 Selenium处理HTML5

3.10.1 处理Vedio

这就需要了解html5中vedio的相关方法了,可以参考http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp

    private static void html5VedioTest(WebDriver driver)
throws InterruptedException {
driver.get("http://videojs.com/");
Thread.sleep(2000);
//找到vedio元素
WebElement vedio = driver.findElement(By.id("preview-player_html5_api"));
//声明js执行器
JavascriptExecutor js = (JavascriptExecutor) driver;
//对vedio这个元素执行播放操作
js.executeScript("arguments[0].play()", vedio);
//为了观察效果暂停5秒
Thread.sleep(5000);
//对vedio这个元素执行暂停操作
js.executeScript("arguments[0].pause()", vedio);
//为了观察效果暂停2秒
Thread.sleep(2000);
//对vedio这个元素执行播放操作
js.executeScript("arguments[0].play()", vedio);
//为了观察效果暂停2秒
Thread.sleep(2000);
//对vedio这个元素执行重新加载视频的操作
js.executeScript("arguments[0].load()", vedio);
//为了观察效果暂停2秒
Thread.sleep(2000);
}

3.10.2 处理Canvas

    private static void Html5CanvasTest(WebDriver driver)
throws InterruptedException {
driver.get("http://literallycanvas.com/");
Thread.sleep(2000);
//找到canvas元素
WebElement canvas = driver.findElement(By.xpath("//*[@id='literally-canvas']//canvas[1]"));
//声明一个操作类
Actions drawPen = new Actions(driver);
//点击并保持不放鼠标 ,按照给定的坐标点移动
drawPen.clickAndHold(canvas).moveByOffset(20, 100).moveByOffset(100, 20).moveByOffset(-20, -100).moveByOffset(-100, -20).release().perform();
Thread.sleep(2000);
}

3.11 表单(Form)

//Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:
WebElement approve = driver.findElement(By.id("approve"));
approve.click();
//或
approve.submit();//只适合于表单的提交

4 其他


返回

4.1 等待元素加载

超时设置

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);     //识别元素时的超时时间
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);  //页面加载时的超时时间
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);  //异步脚本的超时时间
  • 硬性等待  Thread.sleep(int sleeptime);
  • 智能等待
  • 设置等待页面加载完毕
    private static void waitElementTest(WebDriver driver) {
//设置等待页面完全加载的时间是10秒,如果在10秒内加载完毕,剩余时间不在等待
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.get("https://www.baidu.com/");
By inputBox = By.id("kw");
By searchButton = By.id("su");
//智能等待元素加载出来
intelligentWait(driver, 10, inputBox);
//智能等待元素加载出来
intelligentWait(driver, 10, searchButton);
//输入内容
driver.findElement(inputBox).sendKeys("JAVA");
//点击查询
driver.findElement(searchButton).click();
} public static void intelligentWait(WebDriver driver,int timeOut, final By by){
try {
(new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(by);
return element.isDisplayed();
}
});
} catch (TimeoutException e) {
Assert.fail("超时!! " + timeOut + " 秒之后还没找到元素 [" + by + "]",e);
}
}

4.2 执行JS脚本

selenium常用的js总结

有时候我们需要JS脚本来辅助我们进行测试,比如我们用JS赋值或者用js执行点击操作等。执行JS脚本比较适用某些元素不易点击的情况下使用,比如网页内容太长,当前窗口太长,想要点击那些不在当前窗口可以看到元素可以用此方法。

    private static void runJSTest1(WebDriver driver) throws InterruptedException {
String js ="alert(\"hello,this is a alert!\")";
((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js);
Thread.sleep(2000);
} private static void runJSTest2(WebDriver driver)
throws InterruptedException {
driver.get("https://www.baidu.com/");
String js ="arguments[0].click();";
driver.findElement(By.id("kw")).sendKeys("JAVA");
WebElement searchButton = driver.findElement(By.id("su"));
((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js,searchButton);
Thread.sleep(2000);
}

4.3 模拟键盘操作

有时候有些元素不便点击或者做其他的操作,这个时候可以借助selenium提供的Actions类,它可以模拟鼠标和键盘的一些操作,比如点击鼠标右键,左键,移动鼠标等操作。对于这些操作,使用perform()方法进行执行。

    private static void actionsTest(WebDriver driver)
throws InterruptedException {
// 设置等待页面完全加载的时间是10秒,如果在10秒内加载完毕,剩余时间不在等待
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.get("https://www.baidu.com/");
By inputBox = By.id("kw");
By searchButton = By.id("su");
// 智能等待元素加载出来
intelligentWait(driver, 10, inputBox);
// 智能等待元素加载出来
intelligentWait(driver, 10, searchButton);
// 实例化action对象
Actions action = new Actions(driver);
// 通过action模拟键盘输入java关键字到 输入框,只有使用了perform方法才会输入进去
action.sendKeys(driver.findElement(searchButton), "java").perform();
// 鼠标模拟移动到搜索按钮
action.moveToElement(driver.findElement(searchButton)).perform();
// 模拟点击操作
action.click().perform();
Thread.sleep(2000);
}

Selenium Web 自动化 - Selenium常用API的更多相关文章

  1. Selenium Web 自动化 - Selenium(Java)环境搭建

    Selenium Web 自动化 - Selenium(Java)环境搭建 2016-07-29 1 下载JDK JDK下载地址:http://www.oracle.com/technetwork/j ...

  2. Selenium Web 自动化

    1 Selenium Web 自动化 - Selenium(Java)环境搭建 2 Selenium Web 自动化 - 如何找到元素 3 Selenium Web 自动化 - Selenium常用A ...

  3. Selenium Web 自动化 - 如何找到元素

    Selenium Web 自动化 - 如何找到元素 2016-07-29 1. 什么是元素? 元素:http://www.w3school.com.cn/html/html_elements.asp ...

  4. Selenium Web 自动化 - 项目实战(一)

    Selenium Web 自动化 - 测试框架(一) 2016-08-05 目录 1 框架结构雏形2 把Java项目转变成Maven项目3 加入TestNG配置文件4 Eclipse编码修改5 编写代 ...

  5. RobotFramework自动化测试框架-Selenium Web自动化(二)关于在RobotFramework中如何使用Selenium很全的总结(上)

    好久没有继续分享关于自动化测试相关的东西了,自动化在现今的测试领域已经越来越重要了,大部分公司在测试岗位招聘中都需要会相关的自动化测试知识.而 RobotFramework自动化测试框架 是自动化测试 ...

  6. RobotFramework自动化测试框架-Selenium Web自动化(三)关于在RobotFramework中如何使用Selenium很全的总结(下)

    本文紧接着RobotFramework自动化测试框架-Selenium Web自动化(二)关于在RobotFramework中如何使用Selenium很全的总结(上)继续分享RobotFramewor ...

  7. Selenium Web 自动化 - 项目实战(三)

    Selenium Web 自动化 - 项目实战(三) 2016-08-10 目录 1 关键字驱动概述2 框架更改总览3 框架更改详解  3.1 解析新增页面目录  3.2 解析新增测试用例目录  3. ...

  8. Selenium Web 自动化 - 项目持续集成(进阶)

    Selenium Web 自动化 - 项目持续集成(进阶) 2017-03-09 目录 1 背景及目标2 环境配置  2.1 SVN的安装及使用  2.2 新建Jenkins任务3 过程分析 1 背景 ...

  9. Selenium Web 自动化 - 项目持续集成

    Selenium Web 自动化 - 项目持续集成 2017-02-13 目录 1环境准备  1.1 安装git  1.2 安装jenkins  1.3 安装jenkins插件  1.4 jekins ...

随机推荐

  1. UC浏览器中Ajax请求中传递数据的一个坑

    今天突然收到一个bug,有用户在其浏览器环境中一直无法提交内容,使用的是UC浏览器.当换成Chrome时,内容能够正常提交.鉴于本地没有一直使用Firefox 以及Chrome,于是去下载了一个UC ...

  2. ios技术篇:导航栏push遵循的三个规则

    1.如果B视图有一个自定义的左侧按钮(leftBarButtonItem),则会显示这个自定义按钮 2.如果B没有自定义按钮,但是A视图的backBarButtonItem属性有自定义项,则显示这个自 ...

  3. Python中按值来获取指定的键

    转自: https://blog.csdn.net/Jerry_1126/article/details/87907162 Python字典中的键是唯一的,但不同的键可以对应同样的值,比如说uid,可 ...

  4. 如何开发一个npm包并发布

    一.安装nodejs 不多说了,网上教程多得是 二.创建自己的npm包 目录结构 npm-test a.js b.js package.json 开发 为了简单便于理解,就开发一个简单地hello程序 ...

  5. Bzoj5332: [Sdoi2018]旧试题

    国际惯例的题面首先我们进行一些相对显然的数学变化.解释一下第二行的那个变形,如果一个数是ijk的因数,那么它一定能被分解成三部分分别是i,j,k的因数.我们钦定一个质数只能在三部分的一个中出现.如果一 ...

  6. BZOJ.1758.[WC2010]重建计划(分数规划 点分治 单调队列/长链剖分 线段树)

    题目链接 BZOJ 洛谷 点分治 单调队列: 二分答案,然后判断是否存在一条长度在\([L,R]\)的路径满足权值和非负.可以点分治. 对于(距当前根节点)深度为\(d\)的一条路径,可以用其它子树深 ...

  7. [USACO08DEC]Secret Message

    OJ题号: 洛谷2922 思路: 字典树,每个结点记录经过该节点的字符串数cnt和以该结点结尾的字符串数量val. 每次询问时累加经过节点的val值和结尾结点的cnt值. #include<cs ...

  8. Spark MLlib 之 Vector向量深入浅出

    Spark MLlib里面提供了几种基本的数据类型,虽然大部分在调包的时候用不到,但是在自己写算法的时候,还是很需要了解的.MLlib支持单机版本的local vectors向量和martix矩阵,也 ...

  9. php中call_user_func 与 call_user_func_array的使用

    call_user_func()是利用回调函数处理字符串,call_user_func_array是利用回调函数处理数组. // 1. 调用自定义函数 function test($a, $b) { ...

  10. 咖啡之约--体验 SourceAnywhere

    http://www.damingsoft.com/campaign/school-campaign-coffee-code.aspx 必备技能:代码版本控制 不论你是菜鸟还是大牛,想要获得高薪水和高 ...