目录javascript
点击 JDK8下载,根据本身的平台,选择相应的版本进行下载。css
小知识:
Java环境分JDK和JRE ,JDK就是Java Development Kit。简单的说JDK是面向开发人员使用的SDK,它提供了Java的开发
环境和运行环境。JRE是Java Runtime Enviroment是指Java的运行环境,是面向 Java 程序的使用者。html
咱们以 Windows安装JDK为例,双击下载的JDK,设置安装路径。这里我选择默认安装在“D:\Program Files\Java\jdk1.8.0_101”目录下。
下面设置环境变量:
“个人电脑” 右键菜单—>属性—>高级—>环境变量—>系统变量—>新建..前端
变量名: JAVA_HOME
变量值: D:\Program Files\Java\jdk1.8.0_101
变量名: CALSS_PATH
变量值: .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;java
找到 path 变量名—>“编辑” 添加:python
变量名: PATH
变量值: %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;web
在Windows命令提示符(cmd)下验证 Java 是否成功:chrome
> java 用法: java [-options] class [args...] (执行类) 或 java [-options] -jar jarfile [args...] (执行 jar 文件) 其中选项包括: -d32 使用 32 位数据模型 (若是可用) -d64 使用 64 位数据模型 (若是可用) -client 选择 "client" VM -server 选择 "server" VM 默认 VM 是 client. ...... > javac 用法: javac <options> <source files> 其中, 可能的选项包括: -g 生成全部调试信息 -g:none 不生成任何调试信息 -g:{lines,vars,source} 只生成某些调试信息 -nowarn 不生成任何警告 -verbose 输出有关编译器正在执行的操做的消息 -deprecation 输出使用已过期的 API 的源位置 -classpath <路径> 指定查找用户类文件和注释处理程序的位置 .......
能读者当前下载的 Java 版本与本书不一样, 但安装方法是同样的。shell
你可能会问,为何不用Eclipse呢?随着发展IntelliJ IDEA有超越Eclipse的势头,JetBrains公司的IDE基本上已经一统了各家主流编程语言的江湖。考虑到 Java IDE的流行趋势,本书中决定选用IntelliJ IDEA。
固然, 选择什么样的IDE充满着我的喜爱。你依然能够参考其它资料安装Java IDE。这不会影响你阅读该系列文章。 点击IntelliJ IDEA下载,根据本身的平台,选择相应的版本进行下载。
IntelliJ IDEA安装过程省略…
若是第一次打开IntelliJ IDEA,会看到以下界面。apache
点击”Create New Project”选项建立新的Java项目。选择项目类型为Java,而后,继续”Next”。
点击”Finish”结束项目建立完成。
首先,打开IntelliJ IDEA,点击左侧项目列表,在src下面建立包和类文件。
1)右键左侧项目列表 src—>New —> Package 弹出窗口, 输入包的名:javaBase。
2)右键左侧建立的包名:java —>New —> Java Class 弹出窗口, 输入类的名:HelloWorld。
在 HelloWorld.java 文件中编写第一个 Java 程序。
package com.java.base; public class HelloWorld { public static void main(String[] args){ System.out.println("hello world"); } }
输入完成, 点击工具栏 Run 按钮(或在代码文件中右键选择”Run ‘HelloWorld.main()’“)运行, 将会在控制台看到“hello word” 的输出。
点击Selenium下载 连接 你会看到Selenium Standalone Server的介绍:
The Selenium Server is needed in order to run Remote Selenium WebDriver. Selenium 3.X is no longer capable of running Selenium RC directly, rather it does it through emulation and the WebDriverBackedSelenium interface.
Download version 3.4.0
点击版本号进行下载,下载完成将会获得一个selenium-server-standalone-3.4.0.jar文件。
打开IntelliJ IDEA,导入.jar包。
点击菜单栏 File –> Project Structure(快捷键Ctrl + Alt + Shift + s) ,点击 Project Structure界面左侧 的“Modules” 。在“Dependencies” 标签界面下,点击右边绿色的“+” 号,选择第一个选项“JARs or directories…” ,选择相应的 jar 包,点“OK” ,jar包添加成功。
关于Maven安装又是另外一个话题了。你能够参考其它资料学习在IntelliJ IDEA建立Maven项目。
Maven官网、idea & maven help、Maven仓库
打开pom.xml 配置Selenium。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mvn.demo</groupId> <artifactId>MyMvnPro</artifactId> <version>1.0-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> <dependencies> <!-- selenium-java --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.4.0</version> </dependency> </dependencies> </project>
虽然,学习Maven须要增长你的学习成本,但若是你须要长期使用Java编程语言,或者想用Java来作更多事情的话,越早使用Maven越好!由于它会让的第三方包管理变得很是简单。
最后,少不了要写一个简单的Selenium Sample来验证Selenium安装是否成功,打开IntelliJ IDEA 建立一个新类Itest.java
package javaBase; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Itest { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("http://www.itest.info"); String title = driver.getTitle(); System.out.printf(title); driver.close(); } }
若是执行报错,请看下一节,Selenium3浏览器驱动。
当selenium升级到3.0以后,对不一样的浏览器驱动进行了规范。若是想使用selenium驱动不一样的浏览器,必须单独下载并设置不一样的浏览器驱动。
各浏览器下载地址:
设置浏览器的地址很是简单。 咱们能够手动建立一个存放浏览器驱动的目录,如: C:\driver , 将下载的浏览器驱动文件(例如:chromedriver、geckodriver)丢到该目录下。
个人电脑–>属性–>系统设置–>高级–>环境变量–>系统变量–>Path,将“C:\driver”目录添加到Path的值中。
验证不一样的浏览器驱动是否正常使用。
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; …… WebDriver driver = new ChromeDriver(); //Chrome浏览器 WebDriver driver = new FirefoxDriver(); //Firefox浏览器 WebDriver driver = new EdgeDriver(); //Edge浏览器 WebDriver driver = new InternetExplorerDriver(); // Internet Explorer浏览器 WebDriver driver = new OperaDriver(); //Opera浏览器 WebDriver driver = new PhantomJSDriver(); //PhantomJS ……
Selenium提供了8种定位方式。
这8种定位方式在Java selenium中所对应的方法为:
假如咱们有一个Web页面,经过前端工具(如,Firebug)查看到一个元素的属性是这样的。
<html> <head> <body link="#0000cc"> <a id="result_logo" href="/" οnmοusedοwn="return c({'fm':'tab','tab':'logo'})"> <form id="form" class="fm" name="f" action="/s"> <span class="soutu-btn"></span> <input id="kw" class="s_ipt" name="wd" value="" maxlength="255" autocomplete="off">
咱们的目的是要定位input标签的输入框。
//经过id定位: driver.findElement(By.id("kw")) //经过name定位: driver.findElement(By.name("wd")) //经过class name定位: driver.findElement(By.className("s_ipt")) //经过tag name定位: driver.findElement(By.tagName("input")) //经过xpath定位,xpath定位有N种写法,这里列几个经常使用写法: driver.findElement(By.xpath("//*[@id='kw']")) driver.findElement(By.xpath("//*[@name='wd']")) driver.findElement(By.xpath("//input[@class='s_ipt']")) driver.findElement(By.xpath("/html/body/form/span/input")) driver.findElement(By.xpath("//span[@class='soutu-btn']/input")) driver.findElement(By.xpath("//form[@id='form']/span/input")) driver.findElement(By.xpath("//input[@id='kw' and @name='wd']")) //经过css定位,css定位有N种写法,这里列几个经常使用写法: driver.findElement(By.cssSelector("#kw") driver.findElement(By.cssSelector("[name=wd]") driver.findElement(By.cssSelector(".s_ipt") driver.findElement(By.cssSelector("html > body > form > span > input") driver.findElement(By.cssSelector("span.soutu-btn> input#kw") driver.findElement(By.cssSelector("form#form > span > input")
接下来,咱们的页面上有一组文本连接。
<a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a> <a class="mnav" href="http://www.hao123.com" name="tj_trhao123">hao123</a>
//经过link text定位: driver.findElement(By.linkText("新闻") driver.findElement(By.linkText("hao123") //经过partialLink text定位: driver.findElement(By.partialLinkText("新") driver.findElement(By.partialLinkText("hao") driver.findElement(By.partialLinkText("123")
关于xpaht和css的定位比较复杂,请参考: xpath语法、css选择器
有时候咱们但愿能以某种浏览器尺寸找开,访问的页面在这种尺寸下运行。例如能够将浏览器设置成移动端大小(480* 800),而后访问移动站点,对其样式进行评估;WebDriver 提供了 manage().window().setSize()方法来设置浏览器的大小。
import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Browser { public static void main(String[] args) throws InterruptedException { WebDriver driver= new ChromeDriver(); driver.get("https://www.baidu.cn"); driver.manage().window().maximize(); Thread.sleep(2000); driver.get("https://m.baidu.cn"); driver.manage().window().setSize(new Dimension(480, 800)); Thread.sleep(2000); driver.quit(); } }
在 PC 端执行自动化测试脚本大多的状况下是但愿浏览器在全屏幕模式下执行, 那么可使用 maximize()方法使打开的浏览器全屏显示, 其用法与 setSize()相同, 但它不须要任何参数。
在使用浏览器浏览网页时,浏览器提供了后退和前进按钮,能够方便地在浏览过的网页之间切换,WebDriver也提供了对应的back()和forward()方法来模拟后退和前进按钮。下面经过例子来演示这两个方法的使用。
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.By; public class BrowserGo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); //get 到百度首页 driver.get("https://www.baidu.com/"); System.out.printf("now accesss %s \n", driver.getCurrentUrl()); Thread.sleep(2000); //点击“新闻” 连接 driver.findElement(By.linkText("新闻")).click(); System.out.printf("now accesss %s \n", driver.getCurrentUrl()); Thread.sleep(2000); //执行浏览器后退 driver.navigate().back(); System.out.printf("back to %s \n", driver.getCurrentUrl()); Thread.sleep(2000); //执行浏览器前面 driver.navigate().forward(); System.out.printf("forward to %s \n", driver.getCurrentUrl()); Thread.sleep(2000); driver.quit(); } }
为了看清脚本的执行过程,下面每操做一步都经过printf()方法来打印当前的URL地址。
有时候须要手动刷新(F5) 页面。
…… //刷新页面 driver.navigate().refresh(); ……
前面咱们已经学习了定位元素, 定位只是第一步, 定位以后须要对这个元素进行操做, 或单击(按钮) 或 输入(输入框) , 下面就来认识这些最经常使用的方法。
下面先来认识 WebDriver 中最经常使用的几个方法:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class BaiduDemo { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com/"); WebElement search_text = driver.findElement(By.id("kw")); WebElement search_button = driver.findElement(By.id("su")); search_text.sendKeys("Java"); search_text.clear(); search_text.sendKeys("Selenium"); search_button.click(); driver.quit(); } }
clear()方法用于清除文本输入框中的内容。
sendKeys()方法模拟键盘向输入框里输入内容。 可是它的做用不只于此, 咱们还能够用它发送键盘按键, 甚至用它来指定上传的文件。
click()方法能够用来单击一个元素,前提是它是能够被单击的对象,它与 sendKeys()方法是Web页面操做中最经常使用到的两个方法。 其实click()方法不只仅用于单击一个按钮,它还能够单击任何能够单击的文字/图片连接、复选框、单选框、下拉框等。
submit()方法用于提交表单。 例如,在搜索框输入关键字以后的“回车” 操做, 就能够经过 submit()方法模拟.
…… WebElement search_text = driver.findElement(By.id("kw")); search_text.sendKeys("Selenium"); search_text.submit(); ……
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class BaiduDemo { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com/"); //得到百度输入框的尺寸 WebElement size = driver.findElement(By.id("kw")); System.out.println(size.getSize()); //返回百度页面底部备案信息 WebElement text = driver.findElement(By.id("cp")); System.out.println(text.getText()); //返回元素的属性值, 能够是 id、 name、 type 或元素拥有的其它任意属性 WebElement ty = driver.findElement(By.id("kw")); System.out.println(ty.getAttribute("type")); //返回元素的结果是否可见, 返回结果为 True 或 False WebElement display = driver.findElement(By.id("kw")); System.out.println(display.isDisplayed()); driver.quit(); } }
打印结果:
(500, 22) ©2017 Baidu 使用百度前必读 意见反馈 京 ICP 证 030173 号 京公网安备 11000002000001 号 text true
经过前面例子了解到,可使用click()来模拟鼠标的单击操做,如今的Web产品中提供了更丰富的鼠标交互方式, 例如鼠标右击、双击、悬停、甚至是鼠标拖动等功能。在WebDriver中,将这些关于鼠标操做的方法封装在ActionChains类提供。
Actions 类提供了鼠标操做的经常使用方法:
百度首页设置悬停下拉菜单。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class MouseDemo { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com/"); WebElement search_setting = driver.findElement(By.linkText("设置")); Actions action = new Actions(driver); action.clickAndHold(search_setting).perform(); driver.quit(); } }
导入提供鼠标操做的 ActionChains 类
1.关于鼠标操做的其它方法
import org.openqa.selenium.interactions.Actions; …… Actions action = new Actions(driver); // 鼠标右键点击指定的元素 action.contextClick(driver.findElement(By.id("element"))).perform(); // 鼠标右键点击指定的元素 action.doubleClick(driver.findElement(By.id("element"))).perform(); // 鼠标拖拽动做, 将 source 元素拖放到 target 元素的位置。 WebElement source = driver.findElement(By.name("element")); WebElement target = driver.findElement(By.name("element")); action.dragAndDrop(source,target).perform(); // 释放鼠标 action.release().perform();
Keys()类提供了键盘上几乎全部按键的方法。 前面了解到, sendKeys()方法能够用来模拟键盘输入, 除此之 外, 咱们还能够用它来输入键盘上的按键, 甚至是组合键, 如 Ctrl+A、 Ctrl+C 等。
import org.openqa.selenium.WebElement; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.By; import org.openqa.selenium.Keys; public class Keyboard { public static void main(String[] args)throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); WebElement input = driver.findElement(By.id("kw")); //输入框输入内容 input.sendKeys("seleniumm"); Thread.sleep(2000); //删除多输入的一个 m input.sendKeys(Keys.BACK_SPACE); Thread.sleep(2000); //输入空格键+“教程” input.sendKeys(Keys.SPACE); input.sendKeys("教程"); Thread.sleep(2000); //ctrl+a 全选输入框内容 input.sendKeys(Keys.CONTROL,"a"); Thread.sleep(2000); //ctrl+x 剪切输入框内容 input.sendKeys(Keys.CONTROL,"x"); Thread.sleep(2000); //ctrl+v 粘贴内容到输入框 input.sendKeys(Keys.CONTROL,"v"); Thread.sleep(2000); //经过回车键盘来代替点击操做 input.sendKeys(Keys.ENTER); Thread.sleep(2000); driver.quit(); } }
须要说明的是,上面的脚本没有什么实际意义,但向咱们展现了模拟键盘各类按键与组合键的用法。
在使用键盘按键方法前须要先导入 keys 类。
如下为经常使用的键盘操做:
sendKeys(Keys.BACK_SPACE) 回格键(BackSpace)
sendKeys(Keys.SPACE) 空格键(Space)
sendKeys(Keys.TAB) 制表键(Tab)
sendKeys(Keys.ESCAPE) 回退键(Esc)
sendKeys(Keys.ENTER) 回车键(Enter)
sendKeys(Keys.CONTROL,‘a’) 全选(Ctrl+A)
sendKeys(Keys.CONTROL,‘c’) 复制(Ctrl+C)
sendKeys(Keys.CONTROL,‘x’) 剪切(Ctrl+X)
sendKeys(Keys.CONTROL,‘v’) 粘贴(Ctrl+V)
sendKeys(Keys.F1) 键盘 F1
……
sendKeys(Keys.F12) 键盘 F12
不论是在作功能测试仍是自动化测试,最后一步须要拿实际结果与预期进行比较。这个比较的称之为断言。
咱们一般能够经过获取title 、URL和text等信息进行断言。text方法在前面已经讲过,它用于获取标签对之间的文本信息。
下面一样以百度为例,介绍如何获取这些信息。
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class AssertDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); System.out.println("Search before================"); //获取当前的 title 和 url System.out.printf("title of current page is %s\n", driver.getTitle()); System.out.printf("url of current page is %s\n", driver.getCurrentUrl()); //百度搜索 WebElement search = driver.findElement(By.id("kw")); search.sendKeys("Selenium"); search.sendKeys(Keys.ENTER); Thread.sleep(2000); System.out.println("Search after================"); //获取当前的 title 和 url System.out.printf("title of current page is %s\n", driver.getTitle()); System.out.printf("url of current page is %s\n", driver.getCurrentUrl()); //获取第一条搜索结果的标题 WebElement result = driver.findElement(By.xpath("//div[@id='content_left']/div/h3/a")); System.out.println(result.getText()); driver.quit(); } }
打印结果:
Search before================ title of current page is 百度一下, 你就知道 url of current page is https://www.baidu.com/ Search after================ title of current page is Selenium_百度搜索 url of current page is https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=Selenium&rsv_pq=9be 4680700a485c1&rsv_t=e925U%2F%2B9SBTqmRI%2BuARg0%2BTCzrrZWn4jOBJkb1OS2vUjMrZsq5VblQ7toD8 &rqlang=cn&rsv_enter=1&rsv_sug3=8&rsv_sug2=0&inputT=155&rsv_sug4=155 Selenium - Web Browser Automation
WebDriver提供了两种类型的等待:显式等待和隐式等待。
WebDriver提供了显式等待方法,专门针对某个元素进行等待判断。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedCondition; public class TimeOut01 { public static void main(String[]args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); //显式等待, 针对某个元素等待 WebDriverWait wait = new WebDriverWait(driver,10,1); wait.until(new ExpectedCondition<WebElement>(){ @Override public WebElement apply(WebDriver text) { return text.findElement(By.id("kw")); } }).sendKeys("selenium"); driver.findElement(By.id("su")).click(); Thread.sleep(2000); driver.quit(); } }
WebDriverWait类是由WebDirver提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,若是超过设置时间检测不到则抛出异常。具体格式以下: WebDriverWait(driver, 10, 1) driver: 浏览器驱动。 10: 最长超时时间, 默认以秒为单位。 1: 检测的的间隔(步长) 时间, 默认为 0.5s。
WebDriver 提供了几种方法来等待元素。
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; public class TimeOut02 { public static void main(String[] args){ WebDriver driver = new ChromeDriver(); //页面加载超时时间设置为 5s driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS); driver.get("https://www.baidu.com/"); //定位对象时给 10s 的时间, 若是 10s 内还定位不到则抛出异常 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.findElement(By.id("kw")).sendKeys("selenium"); //异步脚本的超时时间设置成 3s driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS); driver.quit(); } }
在第(五)节咱们已经学习了8种定位方法, 那8种定位方法是针对单个元素定位的, WebDriver还提供了另外8种用于定位一组元素的方法。
import org.openqa.selenium.By; ...... findElements(By.id()) findElements(By.name()) findElements(By.className()) findElements(By.tagName()) findElements(By.linkText()) findElements(By.partialLinkText()) findElements(By.xpath()) findElements(By.cssSelector())
定位一组元素的方法与定位单个元素的方法相似,惟一的区别是在单词 findElement 后面多了一个 s 表示复数。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class ElementsDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com/"); WebElement search_text = driver.findElement(By.id("kw")); search_text.sendKeys("selenium"); search_text.submit(); Thread.sleep(2000); //匹配第一页搜索结果的标题, 循环打印 List<WebElement> search_result = driver.findElements(By.xpath("//div/div/h3")); //打印元素的个数 System.out.println(search_result.size()); // 循环打印搜索结果的标题 for(WebElement result : search_result){ System.out.println(result.getText()); } System.out.println("-------我是分割线---------"); //打印第n结果的标题 WebElement text = search_result.get(search_result.size() - 10); System.out.println(text.getText()); driver.quit(); } }
打印结果:
15 selenium java 教程-90 天从入门到高薪「学习必看」 python selenium 视频-90 天从入门到高薪「学习必看」 Selenium - Web Browser Automation 功能自动化测试工具——Selenium 篇 Selenium Documentation — Selenium Documentation selenium + python 自动化测试环境搭建 - 虫师 - 博客园 selenium_百度翻译 Selenium_百度百科 怎样开始用 selenium 进行自动化测试(我的总结)_百度经验 Selenium 官网教程_selenium 自动化测试实践_Selenium_领测软件测试网 Selenium - 开源中国社区 selenium 是什么?_百度知道 selenium-0 基础入学, 先就业后付款! selenium, 亚马逊官网, 正品低价, 货到付款! selenium java 教程-90 天从入门到高薪「学习必看」 -------我是分割线--------- selenium + python 自动化测试环境搭建 - 虫师 - 博客园
在 Web 应用中常常会遇到 frame/iframe 表单嵌套页面的应用, WebDriver 只能在一个页面上对元素识别与 定位, 对于 frame/iframe 表单内嵌页面上的元素没法直接定位。 这时就须要经过 switchTo().frame()方法将当前定 位的主体切换为 frame/iframe 表单的内嵌页面中。
<html> <body> ... <iframe id="x-URS-iframe" ...> <html> <body> ... <input name="email" >
126邮箱登陆框的结构大概是这样子的,想要操做登陆框必需要先切换到iframe表单。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class MailLogin { public static void main(String[] args){ WebDriver driver = new ChromeDriver(); driver.get("http://www.126.com"); WebElement xf = driver.findElement(By.xpath("//*[@id='loginDiv']/iframe")); driver.switchTo().frame(xf); driver.findElement(By.name("email")).clear(); driver.findElement(By.name("email")).sendKeys("username"); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys("password"); driver.findElement(By.id("dologin")).click(); driver.switchTo().defaultContent(); //…… } }
若是完成了在当前表单上的操做,则能够经过switchTo().defaultContent()方法跳出表单。
在页面操做过程当中有时候点击某个连接会弹出新的窗口, 这时就须要主机切换到新打开的窗口上进行操做。WebDriver提供了switchTo().window()方法能够实如今不一样的窗口之间切换。
以百度首页和百度注册页为例,在两个窗口之间的切换以下图。
实现窗口切换的代码以下:
import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class MoreWindows { public static void main(String[] arge) throws InterruptedException{ WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); //得到当前窗口句柄 String search_handle = driver.getWindowHandle(); //打开百度注册窗口 driver.findElement(By.linkText("登陆")).click(); Thread.sleep(3000); driver.findElement(By.linkText("当即注册")).click(); //得到全部窗口句柄 Set<String> handles = driver.getWindowHandles(); //判断是否为注册窗口, 并操做注册窗口上的元素 for(String handle : handles){ if (handle.equals(search_handle)==false){ //切换到注册页面 driver.switchTo().window(handle); System.out.println("now register window!"); Thread.sleep(2000); driver.findElement(By.name("userName")).clear(); driver.findElement(By.name("userName")).sendKeys("user name"); driver.findElement(By.name("phone")).clear(); driver.findElement(By.name("phone")).sendKeys("phone number"); //...... Thread.sleep(2000); //关闭当前窗口 driver.close(); } } Thread.sleep(2000); driver.quit(); } }
在本例中所涉及的新方法以下:
有时咱们会碰到下拉框,WebDriver提供了Select类来处理下接框。
如百度搜索设置的下拉框,以下图:
搜索下拉框实现代码以下:
<select id="nr" name="NR"> <option value="10" selected>每页显示 10 条</option> <option value="20">每页显示 20 条</option> <option value="50">每页显示 50 条</option> <select>
操做下接框代码以下:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class SelectDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); driver.findElement(By.linkText("设置")).click(); driver.findElement(By.linkText("搜索设置")).click(); Thread.sleep(2000); //<select>标签的下拉框选择 WebElement el = driver.findElement(By.xpath("//select")); Select sel = new Select(el); sel.selectByValue("20"); Thread.sleep(2000); driver.quit(); } }
Select类用于定位select标签。 selectByValue()方法符用于选取标签的value值。
在 WebDriver中处理JavaScript所生成的alert、confirm以及prompt十分简单,具体作法是使用switch_to_alert()方法定位到alert/confirm/prompt,而后使用text/accept/dismiss/sendKeys等方法进行操做。
以下图,百度搜索设置弹出的窗口是不能经过前端工具对其进行定位的,这个时候就能够经过switchTo().alert()方法接受这个弹窗。
接受一个警告框的代码以下:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class AlertDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); driver.findElement(By.linkText("设置")).click(); driver.findElement(By.linkText("搜索设置")).click(); Thread.sleep(2000); //保存设置 driver.findElement(By.className("prefpanelgo")).click(); //接收弹窗 driver.switchTo().alert().accept(); Thread.sleep(2000); driver.quit(); } }
对于经过input标签实现的上传功能,能够将其看做是一个输入框,即经过sendKeys()指定本地文件路径的方式实现文件上传。 建立upfile.html文件,代码以下:
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>upload_file</title> <link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div class="row-fluid"> <div class="span6 well"> <h3>upload_file</h3> <input type="file" name="file" /> </div> </div> </body> <script src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></scrip> </html>
经过浏览器打开upfile.html文件,功能以下图。
接下来经过sendKeys()方法来实现文件上传。
import java.io.File; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class UpFileDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); File file = new File("./HTMLFile/upfile.html"); String filePath = file.getAbsolutePath(); driver.get(filePath); //定位上传按钮, 添加本地文件 driver.findElement(By.name("file")).sendKeys("D:\\upload_file.txt"); Thread.sleep(5000); driver.quit(); } }
有时候咱们须要验证浏览器中Cookie是否正确, 由于基于真实Cookie的测试是没法经过白盒测试和集成测试进行的。WebDriver提供了操做Cookie的相关方法能够读取、 添加和删除Cookie信息。
WebDriver 操做Cookie的方法:
下面经过 geCookies()来获取当前浏览器的 cookie 信息。
import java.util.Set; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.Cookie; public class CookieDemo { public static void main(String[] args){ WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); Cookie c1 = new Cookie("name", "key-aaaaaaa"); Cookie c2 = new Cookie("value", "value-bbbbbb"); driver.manage().addCookie(c1); driver.manage().addCookie(c2); //得到 cookie Set<Cookie> coo = driver.manage().getCookies(); System.out.println(coo); //删除全部 cookie //driver.manage().deleteAllCookies(); driver.quit(); } }
打印结果:
[BIDUPSID=82803D3E2DAD0F5342D22C8F96B9E088; expires=星期六, 24 二月 208512:40:10 CST; path=/; domain=.baidu.com, name=key-aaaaaaa; path=/;domain=www.baidu.com, PSTM=1486301167; expires=星期六, 24 二月 2085 12:40:10 CST;path=/; domain=.baidu.com,H_PS_PSSID=1437_21094_21943_22023; path=/;domain=.baidu.com, BD_UPN=12314753; expires=星期三, 15 二月 2017 09:26:04 CST;path=/; domain=www.baidu.com, value=value-bbbbbb; path=/;domain=www.baidu.com,BAIDUID=82803D3E2DAD0F5342D22C8F96B9E088:FG=1; expires=星期六, 24 二月 208512:40:10 CST; path=/; domain=.baidu.com, BD_HOME=0; path=/;domain=www.baidu.com, __bsi=16852840641557463410_00_0_I_R_1_0303_C02F_N_I_I_0;expires=星期日, 05 二月 2017 09:26:10 CST; path=/; domain=.www.baidu.com]
虽然WebDriver提供了操做浏览器的前进和后退方法,但对于浏览器滚动条并无提供相应的操做方法。在这种状况下,就能够借助JavaScript来控制浏览器的滚动条。WebDriver提供了executeScript()方法来执行JavaScript代码。 用于调整浏览器滚动条位置的JavaScript代码以下:
<!-- window.scrollTo(左边距,上边距); --> window.scrollTo(0,450);
window.scrollTo()方法用于设置浏览器窗口滚动条的水平和垂直位置。方法的第一个参数表示水平的左间距,第二个参数表示垂直的上边距。其代码以下:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.Dimension; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; public class JSDemo { public static void main(String[] args) throws InterruptedException{ WebDriver driver = new ChromeDriver(); //设置浏览器窗口大小 driver.manage().window().setSize(new Dimension(700, 600)); driver.get("https://www.baidu.com"); //进行百度搜索 driver.findElement(By.id("kw")).sendKeys("webdriver api"); driver.findElement(By.id("su")).click(); Thread.sleep(2000); //将页面滚动条拖到底部 ((JavascriptExecutor)driver).executeScript("window.scrollTo(100,450);"); Thread.sleep(3000); driver.quit(); } }
经过浏览器打开百度进行搜索,而且提早经过window().setSize()方法将浏览器窗口设置为固定宽高显示,目的是让窗口出现水平和垂直滚动条。而后经过executeScript()方法执行JavaScripts代码来移动滚动条的位置。
自动化用例是由程序去执行,所以有时候打印的错误信息并不十分明确。若是在脚本执行出错的时候能对当前窗口截图保存,那么经过图片就能够很是直观地看出出错的缘由。 WebDriver提供了截图函数getScreenshotAs()来截取当前窗口。
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.TakesScreenshot; public class GetImg { public static void main(String[] arge){ WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(srcFile,new File("d:\\screenshot.png")); } catch (IOException e) { e.printStackTrace(); } driver.quit(); } }
脚本运行完成后打开D盘,就能够找到screenshot.png图片文件了。