详解介绍Selenium的使用--Java语言

 

安装Selenium

1 jar包安装 点击下载jar包,导入到开发工具即可

2 maven安装

<?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>

 

selenium3 浏览器驱动

当selenium升级到3.0之后,对不同的浏览器驱动进行了规范。如果想使用selenium驱动不同的浏览器,必须单独下载并设置不同的浏览器驱动。
各浏览器下载地址:
Firefox浏览器驱动:geckodriver
Chrome浏览器驱动:chromedrivertaobao备用地址
IE浏览器驱动:IEDriverServer
Edge浏览器驱动:MicrosoftWebDriver
Opera浏览器驱动:operadriver
PhantomJS浏览器驱动:phantomjs
注:部分浏览器驱动地址需要科学上网。

 

设置浏览器驱动

1 设置浏览器的地址非常简单。 我们可以手动创建一个存放浏览器驱动的目录,如: C:\driver , 将下载的浏览器驱动文件(例如:chromedriver、geckodriver)丢到该目录下。
我的电脑–>属性–>系统设置–>高级–>环境变量–>系统变量–>Path,将“C:\driver”目录添加到Path的值中。

 2  

chrome:

System.setProperty("webdriver.chrome.driver", "paht\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

 

火狐:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "D:\\Program Files\\Mozilla Firefox\\firefox.exe”);
driver = new FirefoxDriver(profile);

IE:

System.setProperty("webdriver.ie.driver","path\\IEDriverServer.exe");
InternetExplorerDriverService service = (new org.openqa.selenium.ie.InternetExplorerDriverService.Builder()).usingAnyFreePort().build();
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability("ignoreProtectedModeSettings", true);
capabilities.setCapability("unexpectedAlertBehaviour", "accept");
driver = new InternetExplorerDriver(service, capabilities);

 

验证浏览器驱动

验证不同的浏览器驱动是否正常使用。
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

 

 

Hello Selenium

写一个简单的Selenium Sample来验证Selenium安装是否成功。

    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.duheart.cn");

String title = driver.getTitle();
System.out.printf(title);

driver.close();
}
}

 

selenium元素定位

1.selenium定位方法

Selenium提供了8种定位方式。

  • id
  • name
  • class name
  • tag name
  • link text
  • partial link text
  • xpath
  • css selector

这8种定位方式在Java selenium中所对应的方法为:

  • findElement(By.id())
  • findElement(By.name())
  • findElement(By.className())
  • findElement(By.tagName())
  • findElement(By.linkText())
  • findElement(By.partialLinkText())
  • findElement(By.xpath())
  • findElement(By.cssSelector())

2.定位方法的用法

假如我们有一个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种写法,这里列几个常用写法:
    1. driver.findElement(By.xpath("//*[@id='kw']"))
    2. driver.findElement(By.xpath("//*[@name='wd']"))
    3. driver.findElement(By.xpath("//input[@]"))
    4. driver.findElement(By.xpath("/html/body/form/span/input"))
    5. driver.findElement(By.xpath("//span[@]/input"))
    6. driver.findElement(By.xpath("//form[@id='form']/span/input"))
    7. driver.findElement(By.xpath("//input[@id='kw' and @name='wd']"))
  • 通过css定位,css定位有N种写法,这里列几个常用写法:
    1. driver.findElement(By.cssSelector("#kw")
    2. driver.findElement(By.cssSelector("[name=wd]")
    3. driver.findElement(By.cssSelector(".s_ipt")
    4. driver.findElement(By.cssSelector("html > body > form > span > input")
    5. driver.findElement(By.cssSelector("span.soutu-btn> input#kw")
    6. driver.findElement(By.cssSelector("form#form > span > input")

接下来,我们的页面上有一组文本链接。

  1. <a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a>
  2. <a class="mnav" href="http://www.hao123.com" name="tj_trhao123">hao123</a>
  • 通过link text定位:
    1. driver.findElement(By.linkText("新闻")
    2. driver.findElement(By.linkText("hao123")
  • 通过partialLink text定位:
    1. driver.findElement(By.partialLinkText("新")
    2. driver.findElement(By.partialLinkText("hao")
    3. driver.findElement(By.partialLinkText("123")

关于xpaht和css的定位比较复杂,请参考: xpath语法css选择器

 

控制浏览器操作

1.控制浏览器窗口大小

有时候我们希望能以某种浏览器尺寸找开,访问的页面在这种尺寸下运行。例如可以将浏览器设置成移动端大小(480* 800),然后访问移动站点,对其样式进行评估;WebDriver 提供了 manage().window().setSize()方法来设置浏览器的大小。

  • maximize() 设置浏览器最大化
  • setSize() 设置浏览器宽高
  1. import org.openqa.selenium.Dimension;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4.  
  5.  
  6. public class Browser {
  7. public static void main(String[] args) throws InterruptedException {
  8.  
  9. WebDriver driver= new ChromeDriver();
  10. driver.get("https://www.baidu.cn");
  11.  
  12. driver.manage().window().maximize();
  13. Thread.sleep(2000);
  14.  
  15. driver.get("https://m.baidu.cn");
  16. driver.manage().window().setSize(new Dimension(480, 800));
  17. Thread.sleep(2000);
  18.  
  19. driver.quit();
  20. }
  21. }

在 PC 端执行自动化测试脚本大多的情况下是希望浏览器在全屏幕模式下执行, 那么可以使用 maximize()方法使打开的浏览器全屏显示, 其用法与 setSize()相同, 但它不需要任何参数。

2.控制浏览器后退、前进

在使用浏览器浏览网页时,浏览器提供了后退和前进按钮,可以方便地在浏览过的网页之间切换,WebDriver也提供了对应的back()和forward()方法来模拟后退和前进按钮。下面通过例子来演示这两个方法的使用。

  • back() 模拟浏览器后退按钮
  • forward() 模拟浏览器前进按钮
  1. import org.openqa.selenium.WebDriver;
  2. import org.openqa.selenium.chrome.ChromeDriver;
  3. import org.openqa.selenium.By;
  4.  
  5.  
  6. public class BrowserGo {
  7.  
  8. public static void main(String[] args) throws InterruptedException {
  9.  
  10. WebDriver driver = new ChromeDriver();
  11.  
  12. //get 到百度首页
  13. driver.get("https://www.baidu.com/");
  14. System.out.printf("now accesss %s \n", driver.getCurrentUrl());
  15. Thread.sleep(2000);
  16.  
  17. //点击“新闻” 链接
  18. driver.findElement(By.linkText("新闻")).click();
  19. System.out.printf("now accesss %s \n", driver.getCurrentUrl());
  20. Thread.sleep(2000);
  21.  
  22. //执行浏览器后退
  23. driver.navigate().back();
  24. System.out.printf("back to %s \n", driver.getCurrentUrl());
  25. Thread.sleep(2000);
  26.  
  27. //执行浏览器前面
  28. driver.navigate().forward();
  29. System.out.printf("forward to %s \n", driver.getCurrentUrl());
  30. Thread.sleep(2000);
  31.  
  32. driver.quit();
  33. }
  34. }

为了看清脚本的执行过程,下面每操作一步都通过printf()方法来打印当前的URL地址。

3.刷新页面

有时候需要手动刷新(F5) 页面。

  • refresh() 刷新页面(F5)
  1. ……
  2. //刷新页面
  3. driver.navigate().refresh();
  4. ……

WebDriver常用方法

前面我们已经学习了定位元素, 定位只是第一步, 定位之后需要对这个元素进行操作, 或单击(按钮) 或 输入(输入框) , 下面就来认识这些最常用的方法。 

1.WebDriver 常用方法

下面先来认识 WebDriver 中最常用的几个方法:

  • clear() 清除文本。
  • sendKeys(*value) 模拟按键输入。
  • click() 单击元素
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5.  
  6. public class BaiduDemo {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. WebDriver driver = new ChromeDriver();
  11. driver.get("https://www.baidu.com/");
  12.  
  13. WebElement search_text = driver.findElement(By.id("kw"));
  14. WebElement search_button = driver.findElement(By.id("su"));
  15.  
  16. search_text.sendKeys("Java");
  17. search_text.clear();
  18. search_text.sendKeys("Selenium");
  19. search_button.click();
  20.  
  21. driver.quit();
  22. }
  23. }

clear()方法用于清除文本输入框中的内容。
sendKeys()方法模拟键盘向输入框里输入内容。 但是它的作用不仅于此, 我们还可以用它发送键盘按键, 甚至用它来指定上传的文件。
click()方法可以用来单击一个元素,前提是它是可以被单击的对象,它与 sendKeys()方法是Web页面操作中最常用到的两个方法。 其实click()方法不仅仅用于单击一个按钮,它还可以单击任何可以单击的文字/图片链接、复选框、单选框、下拉框等。

2.其它常用方法

  • submit()

submit()方法用于提交表单。 例如,在搜索框输入关键字之后的“回车” 操作, 就可以通过 submit()方法模拟.

  1. ……
  2. WebElement search_text = driver.findElement(By.id("kw"));
  3. search_text.sendKeys("Selenium");
  4. search_text.submit();
  5. ……
  • getSize() 返回元素的尺寸。
  • getText() 获取元素的文本。
  • getAttribute(name) 获得属性值。
  • isDisplayed() 设置该元素是否用户可见。
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5.  
  6. public class BaiduDemo {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. WebDriver driver = new ChromeDriver();
  11. driver.get("https://www.baidu.com/");
  12.  
  13. //获得百度输入框的尺寸
  14. WebElement size = driver.findElement(By.id("kw"));
  15. System.out.println(size.getSize());
  16.  
  17. //返回百度页面底部备案信息
  18. WebElement text = driver.findElement(By.id("cp"));
  19. System.out.println(text.getText());
  20.  
  21. //返回元素的属性值, 可以是 id、 name、 type 或元素拥有的其它任意属性
  22. WebElement ty = driver.findElement(By.id("kw"));
  23. System.out.println(ty.getAttribute("type"));
  24.  
  25. //返回元素的结果是否可见, 返回结果为 True 或 False
  26. WebElement display = driver.findElement(By.id("kw"));
  27. System.out.println(display.isDisplayed());
  28.  
  29. driver.quit();
  30. }
  31. }

打印结果:

  1. (500, 22)
  2. ©2017 Baidu 使用百度前必读 意见反馈 京 ICP 证 030173 号 京公网安备 11000002000001 号
  3. text
  4. true

模拟鼠标操作

通过前面例子了解到,可以使用click()来模拟鼠标的单击操作,现在的Web产品中提供了更丰富的鼠标交互方式, 例如鼠标右击、双击、悬停、甚至是鼠标拖动等功能。在WebDriver中,将这些关于鼠标操作的方法封装在ActionChains类提供。
Actions 类提供了鼠标操作的常用方法:

  • contextClick() 右击
  • clickAndHold() 鼠标点击并控制
  • doubleClick() 双击
  • dragAndDrop() 拖动
  • release() 释放鼠标
  • perform() 执行所有Actions中存储的行为

百度首页设置悬停下拉菜单。

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5. import org.openqa.selenium.interactions.Actions;
  6.  
  7. public class MouseDemo {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. WebDriver driver = new ChromeDriver();
  12. driver.get("https://www.baidu.com/");
  13.  
  14. WebElement search_setting = driver.findElement(By.linkText("设置"));
  15. Actions action = new Actions(driver);
  16. action.clickAndHold(search_setting).perform();
  17.  
  18. driver.quit();
  19. }
  20. }
  • import org.openqa.selenium.interactions.Actions;

导入提供鼠标操作的 ActionChains 类

  • Actions(driver) 调用Actions()类,将浏览器驱动driver作为参数传入。
  • clickAndHold() 方法用于模拟鼠标悬停操作, 在调用时需要指定元素定位。
  • perform() 执行所有ActionChains中存储的行为, 可以理解成是对整个操作的提交动作。

1.关于鼠标操作的其它方法

  1. import org.openqa.selenium.interactions.Actions;
  2. ……
  3.  
  4. Actions action = new Actions(driver);
  5.  
  6. // 鼠标右键点击指定的元素
  7. action.contextClick(driver.findElement(By.id("element"))).perform();
  8.  
  9. // 鼠标右键点击指定的元素
  10. action.doubleClick(driver.findElement(By.id("element"))).perform();
  11.  
  12. // 鼠标拖拽动作, 将 source 元素拖放到 target 元素的位置。
  13. WebElement source = driver.findElement(By.name("element"));
  14. WebElement target = driver.findElement(By.name("element"));
  15. action.dragAndDrop(source,target).perform();
  16.  
  17. // 释放鼠标
  18. action.release().perform();

模拟键盘操作

Keys()类提供了键盘上几乎所有按键的方法。 前面了解到, sendKeys()方法可以用来模拟键盘输入, 除此之 外, 我们还可以用它来输入键盘上的按键, 甚至是组合键, 如 Ctrl+A、 Ctrl+C 等。

  1. import org.openqa.selenium.WebElement;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. import org.openqa.selenium.By;
  5. import org.openqa.selenium.Keys;
  6.  
  7. public class Keyboard {
  8.  
  9. public static void main(String[] args)throws InterruptedException {
  10.  
  11. WebDriver driver = new ChromeDriver();
  12. driver.get("https://www.baidu.com");
  13.  
  14. WebElement input = driver.findElement(By.id("kw"));
  15.  
  16. //输入框输入内容
  17. input.sendKeys("seleniumm");
  18. Thread.sleep(2000);
  19.  
  20. //删除多输入的一个 m
  21. input.sendKeys(Keys.BACK_SPACE);
  22. Thread.sleep(2000);
  23.  
  24. //输入空格键+“教程”
  25. input.sendKeys(Keys.SPACE);
  26. input.sendKeys("教程");
  27. Thread.sleep(2000);
  28.  
  29. //ctrl+a 全选输入框内容
  30. input.sendKeys(Keys.CONTROL,"a");
  31. Thread.sleep(2000);
  32.  
  33. //ctrl+x 剪切输入框内容
  34. input.sendKeys(Keys.CONTROL,"x");
  35. Thread.sleep(2000);
  36.  
  37. //ctrl+v 粘贴内容到输入框
  38. input.sendKeys(Keys.CONTROL,"v");
  39. Thread.sleep(2000);
  40.  
  41. //通过回车键盘来代替点击操作
  42. input.sendKeys(Keys.ENTER);
  43. Thread.sleep(2000);
  44.  
  45. driver.quit();
  46. }
  47. }

需要说明的是,上面的脚本没有什么实际意义,但向我们展示了模拟键盘各种按键与组合键的用法。

  • import org.openqa.selenium.Keys;

在使用键盘按键方法前需要先导入 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方法在前面已经讲过,它用于获取标签对之间的文本信息。

  • getTitle(): 用于获得当前页面的title。
  • getCurrentUrl() : 用户获得当前页面的URL。
  • getText() 获取页面文本信息。

下面同样以百度为例,介绍如何获取这些信息。

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.Keys;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.WebElement;
  5. import org.openqa.selenium.chrome.ChromeDriver;
  6.  
  7.  
  8. public class AssertDemo {
  9.  
  10. public static void main(String[] args) throws InterruptedException {
  11.  
  12. WebDriver driver = new ChromeDriver();
  13. driver.get("https://www.baidu.com");
  14.  
  15. System.out.println("Search before================");
  16.  
  17. //获取当前的 title 和 url
  18. System.out.printf("title of current page is %s\n", driver.getTitle());
  19. System.out.printf("url of current page is %s\n", driver.getCurrentUrl());
  20.  
  21. //百度搜索
  22. WebElement search = driver.findElement(By.id("kw"));
  23. search.sendKeys("Selenium");
  24. search.sendKeys(Keys.ENTER);
  25. Thread.sleep(2000);
  26.  
  27. System.out.println("Search after================");
  28.  
  29. //获取当前的 title 和 url
  30. System.out.printf("title of current page is %s\n", driver.getTitle());
  31. System.out.printf("url of current page is %s\n", driver.getCurrentUrl());
  32.  
  33. //获取第一条搜索结果的标题
  34. WebElement result = driver.findElement(By.xpath("//div[@id='content_left']/div/h3/a"));
  35. System.out.println(result.getText());
  36.  
  37. driver.quit();
  38. }
  39. }

打印结果:

  1. Search before================
  2. title of current page is 百度一下, 你就知道
  3. url of current page is https://www.baidu.com/
  4.  
  5. Search after================
  6. title of current page is Selenium_百度搜索
  7. url of current page is
  8. https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=Selenium&rsv_pq=9be
  9. 4680700a485c1&rsv_t=e925U%2F%2B9SBTqmRI%2BuARg0%2BTCzrrZWn4jOBJkb1OS2vUjMrZsq5VblQ7toD8
  10. &rqlang=cn&rsv_enter=1&rsv_sug3=8&rsv_sug2=0&inputT=155&rsv_sug4=155
  11. Selenium - Web Browser Automation

设置元素等待

WebDriver提供了两种类型的等待:显式等待和隐式等待。

1.显示等待

WebDriver提供了显式等待方法,专门针对某个元素进行等待判断。

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5. import org.openqa.selenium.support.ui.WebDriverWait;
  6. import org.openqa.selenium.support.ui.ExpectedCondition;
  7.  
  8.  
  9. public class TimeOut01 {
  10.  
  11. public static void main(String[]args) throws InterruptedException {
  12.  
  13. WebDriver driver = new ChromeDriver();
  14. driver.get("https://www.baidu.com");
  15.  
  16. //显式等待, 针对某个元素等待
  17. WebDriverWait wait = new WebDriverWait(driver,10,1);
  18.  
  19. wait.until(new ExpectedCondition<WebElement>(){
  20. @Override
  21. public WebElement apply(WebDriver text) {
  22. return text.findElement(By.id("kw"));
  23. }
  24. }).sendKeys("selenium");
  25.  
  26. driver.findElement(By.id("su")).click();
  27. Thread.sleep(2000);
  28.  
  29. driver.quit();
  30. }
  31. }

WebDriverWait类是由WebDirver提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常。具体格式如下:
WebDriverWait(driver, 10, 1)
driver: 浏览器驱动。 10: 最长超时时间, 默认以秒为单位。 1: 检测的的间隔(步长) 时间, 默认为 0.5s。

2.隐式等待

WebDriver 提供了几种方法来等待元素。

  • implicitlyWait。识别对象时的超时时间。过了这个时间如果对象还没找到的话就会抛出NoSuchElement异常。
  • setScriptTimeout。异步脚本的超时时间。WebDriver可以异步执行脚本,这个是设置异步执行脚本脚本返回结果的超时时间。
  • pageLoadTimeout。页面加载时的超时时间。因为WebDriver会等页面加载完毕再进行后面的操作,所以如果页面超过设置时间依然没有加载完成,那么WebDriver就会抛出异常。
  1. import org.openqa.selenium.chrome.ChromeDriver;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.By;
  4. import java.util.concurrent.TimeUnit;
  5.  
  6. public class TimeOut02 {
  7.  
  8. public static void main(String[] args){
  9.  
  10. WebDriver driver = new ChromeDriver();
  11.  
  12. //页面加载超时时间设置为 5s
  13. driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
  14. driver.get("https://www.baidu.com/");
  15.  
  16. //定位对象时给 10s 的时间, 如果 10s 内还定位不到则抛出异常
  17. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  18. driver.findElement(By.id("kw")).sendKeys("selenium");
  19.  
  20. //异步脚本的超时时间设置成 3s
  21. driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS);
  22.  
  23. driver.quit();
  24. }
  25. }

定位一组元素

在第(五)节我们已经学习了8种定位方法, 那8种定位方法是针对单个元素定位的, WebDriver还提供了另外8种用于定位一组元素的方法。

  1. import org.openqa.selenium.By;
  2. ......
  3. findElements(By.id())
  4. findElements(By.name())
  5. findElements(By.className())
  6. findElements(By.tagName())
  7. findElements(By.linkText())
  8. findElements(By.partialLinkText())
  9. findElements(By.xpath())
  10. findElements(By.cssSelector())

定位一组元素的方法与定位单个元素的方法类似,唯一的区别是在单词 findElement 后面多了一个 s 表示复数。

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5. import java.util.List;
  6.  
  7.  
  8. public class ElementsDemo {
  9.  
  10. public static void main(String[] args) throws InterruptedException {
  11.  
  12. WebDriver driver = new ChromeDriver();
  13. driver.get("https://www.baidu.com/");
  14.  
  15. WebElement search_text = driver.findElement(By.id("kw"));
  16. search_text.sendKeys("selenium");
  17. search_text.submit();
  18. Thread.sleep(2000);
  19.  
  20. //匹配第一页搜索结果的标题, 循环打印
  21. List<WebElement> search_result = driver.findElements(By.xpath("//div/div/h3"));
  22.  
  23. //打印元素的个数
  24. System.out.println(search_result.size());
  25.  
  26. // 循环打印搜索结果的标题
  27. for(WebElement result : search_result){
  28. System.out.println(result.getText());
  29. }
  30.  
  31. System.out.println("-------我是分割线---------");
  32.  
  33. //打印第n结果的标题
  34. WebElement text = search_result.get(search_result.size() - 10);
  35. System.out.println(text.getText());
  36.  
  37. driver.quit();
  38. }
  39. }

打印结果:

  1. 15
  2. selenium java 教程-90 天从入门到高薪「学习必看」
  3. python selenium 视频-90 天从入门到高薪「学习必看」
  4. Selenium - Web Browser Automation
  5. 功能自动化测试工具——Selenium 篇
  6. Selenium Documentation — Selenium Documentation
  7. selenium + python 自动化测试环境搭建 - 虫师 - 博客园
  8. selenium_百度翻译
  9. Selenium_百度百科
  10. 怎样开始用 selenium 进行自动化测试(个人总结)_百度经验
  11. Selenium 官网教程_selenium 自动化测试实践_Selenium_领测软件测试网
  12. Selenium - 开源中国社区
  13. selenium 是什么?_百度知道
  14. selenium-0 基础入学, 先就业后付款!
  15. selenium, 亚马逊官网, 正品低价, 货到付款!
  16. selenium java 教程-90 天从入门到高薪「学习必看」
  17. -------我是分割线---------
  18. selenium + python 自动化测试环境搭建 - 虫师 - 博客园

多表单切换

在 Web 应用中经常会遇到 frame/iframe 表单嵌套页面的应用, WebDriver 只能在一个页面上对元素识别与 定位, 对于 frame/iframe 表单内嵌页面上的元素无法直接定位。 这时就需要通过 switchTo().frame()方法将当前定 位的主体切换为 frame/iframe 表单的内嵌页面中。

  1. <html>
  2. <body>
  3. ...
  4. <iframe id="x-URS-iframe" ...>
  5. <html>
  6. <body>
  7. ...
  8. <input name="email" >

126邮箱登录框的结构大概是这样子的,想要操作登录框必须要先切换到iframe表单。

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5.  
  6.  
  7. public class MailLogin {
  8.  
  9. public static void main(String[] args){
  10.  
  11. WebDriver driver = new ChromeDriver();
  12. driver.get("http://www.126.com");
  13.  
  14. WebElement xf = driver.findElement(By.xpath("//*[@id='loginDiv']/iframe"));
  15. driver.switchTo().frame(xf);
  16. driver.findElement(By.name("email")).clear();
  17. driver.findElement(By.name("email")).sendKeys("username");
  18. driver.findElement(By.name("password")).clear();
  19. driver.findElement(By.name("password")).sendKeys("password");
  20. driver.findElement(By.id("dologin")).click();
  21. driver.switchTo().defaultContent();
  22. //……
  23. }
  24. }

如果完成了在当前表单上的操作,则可以通过switchTo().defaultContent()方法跳出表单。

多窗口切换

在页面操作过程中有时候点击某个链接会弹出新的窗口, 这时就需要主机切换到新打开的窗口上进行操作。WebDriver提供了switchTo().window()方法可以实现在不同的窗口之间切换。
以百度首页和百度注册页为例,在两个窗口之间的切换如下图。

实现窗口切换的代码如下:

  1. import java.util.Set;
  2. import org.openqa.selenium.By;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5.  
  6. public class MoreWindows {
  7.  
  8. public static void main(String[] arge) throws InterruptedException{
  9.  
  10. WebDriver driver = new ChromeDriver();
  11. driver.get("https://www.baidu.com");
  12.  
  13. //获得当前窗口句柄
  14. String search_handle = driver.getWindowHandle();
  15.  
  16. //打开百度注册窗口
  17. driver.findElement(By.linkText("登录")).click();
  18. Thread.sleep(3000);
  19. driver.findElement(By.linkText("立即注册")).click();
  20.  
  21. //获得所有窗口句柄
  22. Set<String> handles = driver.getWindowHandles();
  23.  
  24. //判断是否为注册窗口, 并操作注册窗口上的元素
  25. for(String handle : handles){
  26. if (handle.equals(search_handle)==false){
  27. //切换到注册页面
  28. driver.switchTo().window(handle);
  29. System.out.println("now register window!");
  30. Thread.sleep(2000);
  31. driver.findElement(By.name("userName")).clear();
  32. driver.findElement(By.name("userName")).sendKeys("user name");
  33. driver.findElement(By.name("phone")).clear();
  34. driver.findElement(By.name("phone")).sendKeys("phone number");
  35. //......
  36. Thread.sleep(2000);
  37. //关闭当前窗口
  38. driver.close();
  39. }
  40. }
  41. Thread.sleep(2000);
  42.  
  43. driver.quit();
  44. }
  45. }

在本例中所涉及的新方法如下:

  • getWindowHandle(): 获得当前窗口句柄。
  • getWindowHandles(): 返回的所有窗口的句柄到当前会话。
  • switchTo().window(): 用于切换到相应的窗口,与上一节的switchTo().frame()类似,前者用于不同窗口的切换, 后者用于不同表单之间的切换。

下拉框选择

有时我们会碰到下拉框,WebDriver提供了Select类来处理下接框。
如百度搜索设置的下拉框,如下图:


搜索下拉框实现代码如下:

  1. <select id="nr" name="NR">
  2. <option value="10" selected>每页显示 10 条</option>
  3. <option value="20">每页显示 20 条</option>
  4. <option value="50">每页显示 50 条</option>
  5. <select>

操作下接框代码如下:

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5. import org.openqa.selenium.support.ui.Select;
  6.  
  7.  
  8. public class SelectDemo {
  9.  
  10. public static void main(String[] args) throws InterruptedException {
  11.  
  12. WebDriver driver = new ChromeDriver();
  13. driver.get("https://www.baidu.com");
  14.  
  15. driver.findElement(By.linkText("设置")).click();
  16. driver.findElement(By.linkText("搜索设置")).click();
  17. Thread.sleep(2000);
  18.  
  19. //<select>标签的下拉框选择
  20. WebElement el = driver.findElement(By.xpath("//select"));
  21. Select sel = new Select(el);
  22. sel.selectByValue("20");
  23. Thread.sleep(2000);
  24.  
  25. driver.quit();
  26. }
  27. }

Select类用于定位select标签。 selectByValue()方法符用于选取<option>标签的value值。

警告框处理

在 WebDriver中处理JavaScript所生成的alert、confirm以及prompt十分简单,具体做法是使用switch_to_alert()方法定位到alert/confirm/prompt,然后使用text/accept/dismiss/sendKeys等方法进行操作。

  • getText(): 返回 alert/confirm/prompt 中的文字信息。
  • accept(): 接受现有警告框。
  • dismiss(): 解散现有警告框。
  • sendKeys(keysToSend): 发送文本至警告框。
  • keysToSend: 将文本发送至警告框。

如下图,百度搜索设置弹出的窗口是不能通过前端工具对其进行定位的,这个时候就可以通过switchTo().alert()方法接受这个弹窗。

接受一个警告框的代码如下:

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4.  
  5.  
  6. public class AlertDemo {
  7.  
  8. public static void main(String[] args) throws InterruptedException {
  9.  
  10. WebDriver driver = new ChromeDriver();
  11. driver.get("https://www.baidu.com");
  12.  
  13. driver.findElement(By.linkText("设置")).click();
  14. driver.findElement(By.linkText("搜索设置")).click();
  15. Thread.sleep(2000);
  16.  
  17. //保存设置
  18. driver.findElement(By.className("prefpanelgo")).click();
  19.  
  20. //接收弹窗
  21. driver.switchTo().alert().accept();
  22. Thread.sleep(2000);
  23.  
  24. driver.quit();
  25. }
  26. }

文件上传

对于通过input标签实现的上传功能,可以将其看作是一个输入框,即通过sendKeys()指定本地文件路径的方式实现文件上传。
创建upfile.html文件,代码如下:

  1. <html>
  2. <head>
  3. <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  4. <title>upload_file</title>
  5. <link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />
  6. </head>
  7. <body>
  8. <div class="row-fluid">
  9. <div class="span6 well">
  10. <h3>upload_file</h3>
  11. <input type="file" name="file" />
  12. </div>
  13. </div>
  14. </body>
  15. <script src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></scrip>
  16. </html>

通过浏览器打开upfile.html文件,功能如下图。

接下来通过sendKeys()方法来实现文件上传。

  1. import java.io.File;
  2. import org.openqa.selenium.By;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5.  
  6.  
  7. public class UpFileDemo {
  8.  
  9. public static void main(String[] args) throws InterruptedException {
  10.  
  11. WebDriver driver = new ChromeDriver();
  12. File file = new File("./HTMLFile/upfile.html");
  13. String filePath = file.getAbsolutePath();
  14. driver.get(filePath);
  15.  
  16. //定位上传按钮, 添加本地文件
  17. driver.findElement(By.name("file")).sendKeys("D:\\upload_file.txt");
  18. Thread.sleep(5000);
  19.  
  20. driver.quit();
  21. }
  22. }

浏览器cookie操作

有时候我们需要验证浏览器中Cookie是否正确, 因为基于真实Cookie的测试是无法通过白盒测试和集成测试进行的。WebDriver提供了操作Cookie的相关方法可以读取、 添加和删除Cookie信息。
WebDriver 操作Cookie的方法:

  • getCookies() 获得所有 cookie 信息。
  • getCookieNamed(String name) 返回字典的key为“name”的Cookie信息。
  • addCookie(cookie dict) 添加Cookie。“cookie_dict”指字典对象,必须有 name和value值。
  • deleteCookieNamed(String name) 删除Cookie 信息。 “name”是要删除的 cookie的名称; “optionsString” 是该Cookie的选项,目前支持的选项包括“路径” , “域” 。
  • deleteAllCookies() 删除所有 cookie 信息。

下面通过 geCookies()来获取当前浏览器的 cookie 信息。

  1. import java.util.Set;
  2. import org.openqa.selenium.chrome.ChromeDriver;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.Cookie;
  5.  
  6.  
  7. public class CookieDemo {
  8.  
  9. public static void main(String[] args){
  10.  
  11. WebDriver driver = new ChromeDriver();
  12. driver.get("https://www.baidu.com");
  13.  
  14. Cookie c1 = new Cookie("name", "key-aaaaaaa");
  15. Cookie c2 = new Cookie("value", "value-bbbbbb");
  16. driver.manage().addCookie(c1);
  17. driver.manage().addCookie(c2);
  18.  
  19. //获得 cookie
  20. Set<Cookie> coo = driver.manage().getCookies();
  21. System.out.println(coo);
  22.  
  23. //删除所有 cookie
  24. //driver.manage().deleteAllCookies();
  25.  
  26. driver.quit();
  27. }
  28. }

打印结果:

[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]

调用JavaScript代码

虽然WebDriver提供了操作浏览器的前进和后退方法,但对于浏览器滚动条并没有提供相应的操作方法。在这种情况下,就可以借助JavaScript来控制浏览器的滚动条。WebDriver提供了executeScript()方法来执行JavaScript代码。
用于调整浏览器滚动条位置的JavaScript代码如下:

  1. <!-- window.scrollTo(左边距,上边距); -->
  2. window.scrollTo(0,450);

window.scrollTo()方法用于设置浏览器窗口滚动条的水平和垂直位置。方法的第一个参数表示水平的左间距,第二个参数表示垂直的上边距。其代码如下:

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.Dimension;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5. import org.openqa.selenium.JavascriptExecutor;
  6.  
  7.  
  8. public class JSDemo {
  9.  
  10.  
  11. public static void main(String[] args) throws InterruptedException{
  12.  
  13.  
  14. WebDriver driver = new ChromeDriver();
  15.  
  16.  
  17. //设置浏览器窗口大小
  18. driver.manage().window().setSize(new Dimension(700, 600));
  19. driver.get("https://www.baidu.com");
  20.  
  21.  
  22. //进行百度搜索
  23. driver.findElement(By.id("kw")).sendKeys("webdriver api");
  24. driver.findElement(By.id("su")).click();
  25. Thread.sleep(2000);
  26.  
  27.  
  28. //将页面滚动条拖到底部
  29. ((JavascriptExecutor)driver).executeScript("window.scrollTo(100,450);");
  30. Thread.sleep(3000);
  31.  
  32.  
  33. driver.quit();
  34. }
  35. }

通过浏览器打开百度进行搜索,并且提前通过window().setSize()方法将浏览器窗口设置为固定宽高显示,目的是让窗口出现水平和垂直滚动条。然后通过executeScript()方法执行JavaScripts代码来移动滚动条的位置。

获取窗口截图

自动化用例是由程序去执行,因此有时候打印的错误信息并不十分明确。如果在脚本执行出错的时候能对当前窗口截图保存,那么通过图片就可以非常直观地看出出错的原因。 WebDriver提供了截图函数getScreenshotAs()来截取当前窗口。

  1. import java.io.File;
  2. import java.io.IOException;
  3. import org.apache.commons.io.FileUtils;
  4. import org.openqa.selenium.OutputType;
  5. import org.openqa.selenium.WebDriver;
  6. import org.openqa.selenium.chrome.ChromeDriver;
  7. import org.openqa.selenium.TakesScreenshot;
  8.  
  9. public class GetImg {
  10.  
  11. public static void main(String[] arge){
  12.  
  13. WebDriver driver = new ChromeDriver();
  14. driver.get("https://www.baidu.com");
  15.  
  16. File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  17. try {
  18. FileUtils.copyFile(srcFile,new File("d:\\screenshot.png"));
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22.  
  23. driver.quit();
  24. }
  25. }

脚本运行完成后打开D盘,就可以找到screenshot.png图片文件了。