一、java(jdk)安裝
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;
找到 path 變量名—>“編輯” 添加:
變量名: PATH
變量值: %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;
運行:java -verison
同時安裝maven:
二、selenium環境安裝
先創建一個 maven項目
添加selenium依賴:
<!-- selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
完整pom.xml:
<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.imddysc</groupId>
<artifactId>seleniumtest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>seleniumtest</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</project>
編寫HelloWorld 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.itest.info");
String title = driver.getTitle();
System.out.printf(title);
driver.close();
}
}
如果啓動不了,報錯。則爲驅動問題,需要安裝驅動。
添加logback.xml的logback配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<property name="logback.logdir" value="/logs/seleniumtest" />
<property name="logback.appname" value="seleniumtest"/>
<appender name="consoleLog"
class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</layout>
</appender>
<appender name="fileInfoLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 滾動策略 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路徑 -->
<fileNamePattern>${logback.logdir}/info.${logback.appname}.%d.log</fileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
</appender>
<appender name="fileDebugLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 設置滾動策略 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路徑 -->
<fileNamePattern>${logback.logdir}/debug.${logback.appname}.%d.log</fileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
</appender>
<appender name="fileWarnLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 設置滾動策略 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路徑 -->
<fileNamePattern>${logback.logdir}/warn.${logback.appname}.%d.log</fileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
</appender>
<appender name="fileErrorLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 設置滾動策略 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路徑 -->
<fileNamePattern>${logback.logdir}/error.${logback.appname}.%d.log</fileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="consoleLog" />
<appender-ref ref="fileInfoLog" />
<appender-ref ref="fileDebugLog" />
<appender-ref ref="fileWarnLog" />
<appender-ref ref="fileErrorLog" />
</root>
</configuration>
三、Selenium3瀏覽器驅動安裝
下載對應驅動
首先看chrome版本,
當selenium升級到3.0之後,對不同的瀏覽器驅動進行了規範。如果想使用selenium驅動不同的瀏覽器,必須單獨下載並設置不同的瀏覽器驅動。
各瀏覽器下載地址:
Firefox瀏覽器驅動:geckodriver
Chrome瀏覽器驅動:chromedriver taobao備用地址 https://npm.taobao.org/mirrors/chromedriver/95.0.4638.69/chromedriver_win32.zip
IE瀏覽器驅動:IEDriverServer
Edge瀏覽器驅動:MicrosoftWebDriver
Opera瀏覽器驅動:operadriver
PhantomJS瀏覽器驅動:phantomjs
設置瀏覽器驅動
設置瀏覽器的地址非常簡單。 我們可以手動創建一個存放瀏覽器驅動的目錄,如: 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
……
四、測試結果
程序:
package com.imddysc.seleniumtest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 Itest {
private static final Logger logger = LoggerFactory.getLogger(Itest.class);
public static void main(String[] args) throws InterruptedException, IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\xiongwei.dai\\Desktop\\a.txt"));
String contentLine;
List<String> arr1 = new ArrayList();
while ((contentLine = br.readLine()) != null) {
arr1.add(contentLine);
}
WebDriver driver = new ChromeDriver();
driver.get("http://www.anfutong.com/");
WebElement nameElement = driver.findElement(By.name("username"));
WebElement passwordElement = driver.findElement(By.name("password"));
WebElement loginElement = driver.findElement(By.id("btnLogin"));
nameElement.sendKeys("[email protected]");
passwordElement.sendKeys("password");
loginElement.click();
Thread.sleep(2000);
WebElement link1 = driver.findElement(By.linkText("開發配置"));
link1.click();
Thread.sleep(4000);
WebElement link2 = driver.findElement(By.id("_SideBarItem_26"));
link2.click();
Thread.sleep(3000);
for(int i = 0; i < arr1.size(); i++ ) {
String hetong = arr1.get(i);
System.out.println("當前處理單號: " + hetong);
logger.info("當前合同號: " + hetong);
//設置值,刪除原有值設置新值
WebElement input = driver.findElement(By.id("f70"));
input.clear();
input.sendKeys(Keys.chord(Keys.CONTROL, "a"));
input.sendKeys(Keys.DELETE);
Thread.sleep(1000);
input.clear();
input.sendKeys(hetong);
WebElement link3 = driver.findElement(By.linkText("搜索"));
link3.click();
Thread.sleep(3000);
WebElement link4 = driver.findElement(By.linkText(hetong));
link4.click();
Thread.sleep(3000);
WebElement link5 = driver.findElement(By.linkText("編輯"));
link5.click();
Thread.sleep(10000);
//WebElement inputemail = driver.findElement(By.id("f5736"));
//inputemail.sendKeys("1");
//Thread.sleep(3000);
//設置值
WebElement inputemail = driver.findElement(By.xpath("/html/body/div[1]/div/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div[3]/div/table/tbody/tr[1]/td/div/table/tbody/tr[2]/td/div/div[1]/div/table/tbody/tr[2]/td/div/table/tbody/tr/td/div/table/tbody/tr/td[2]/div/table/tbody/tr/td/div/table/tbody/tr[1]/td/div/table/tbody/tr/td/div/form/div[25]/div/div[4]/div/input"));
inputemail.sendKeys("1");
Thread.sleep(3000);
// WebElement link6 = driver.findElement(By.linkText("取消"));
// link6.click();
// Thread.sleep(3000);
WebElement link6 = driver.findElement(By.linkText("保存"));
link6.click();
Thread.sleep(3000);
//關閉
WebElement link7 = driver.findElement(By.xpath("/html/body/div[1]/div/table/tbody/tr/td[2]/div/table/tbody/tr[1]/td/div/ul/li[5]/a/span"));
link7.click();
Thread.sleep(3000);
}
// WebElement input = driver.findElement(By.id("f70"));
// input.sendKeys("110516080600651657");
//
// WebElement link3 = driver.findElement(By.linkText("搜索"));
// link3.click();
//
// Thread.sleep(3000);
// WebElement link4 = driver.findElement(By.linkText("110516080600651657"));
// link4.click();
// Thread.sleep(3000);
//
// WebElement link5 = driver.findElement(By.linkText("編輯"));
// link5.click();
// Thread.sleep(3000);
//
// WebElement inputemail = driver.findElement(By.id("f5736"));
// inputemail.sendKeys("1");
// Thread.sleep(3000);
//
// WebElement link6 = driver.findElement(By.linkText("保存"));
// link6.click();
// Thread.sleep(3000);
Thread.sleep(3000);
System.out.print("操作完成。");
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="/" onmousedown="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選擇器
六、控制瀏覽器操作
1.控制瀏覽器窗口大小
有時候我們希望能以某種瀏覽器尺寸找開,訪問的頁面在這種尺寸下運行。例如可以將瀏覽器設置成移動端大小(480* 800),然後訪問移動站點,對其樣式進行評估;WebDriver 提供了 manage().window().setSize()方法來設置瀏覽器的大小。
- maximize() 設置瀏覽器最大化
- 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()相同, 但它不需要任何參數。
2.控制瀏覽器後退、前進
在使用瀏覽器瀏覽網頁時,瀏覽器提供了後退和前進按鈕,可以方便地在瀏覽過的網頁之間切換,WebDriver也提供了對應的back()和forward()方法來模擬後退和前進按鈕。下面通過例子來演示這兩個方法的使用。
- 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地址。
3.刷新頁面
有時候需要手動刷新(F5) 頁面。
- refresh() 刷新頁面(F5)
…… //刷新頁面 driver.navigate().refresh(); ……
七、WebDriver常用方法
前面我們已經學習了定位元素, 定位只是第一步, 定位之後需要對這個元素進行操作, 或單擊(按鈕) 或 輸入(輸入框) , 下面就來認識這些最常用的方法。
1.WebDriver 常用方法
下面先來認識 WebDriver 中最常用的幾個方法:
- clear() 清除文本。
- sendKeys(*value) 模擬按鍵輸入。
- click() 單擊元素
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()方法不僅僅用於單擊一個按鈕,它還可以單擊任何可以單擊的文字/圖片鏈接、複選框、單選框、下拉框等。
2.其它常用方法
- submit()
submit()方法用於提交表單。 例如,在搜索框輸入關鍵字之後的“回車” 操作, 就可以通過 submit()方法模擬.
……
WebElement search_text = driver.findElement(By.id("kw"));
search_text.sendKeys("Selenium");
search_text.submit();
……
- getSize() 返回元素的尺寸。
- getText() 獲取元素的文本。
- getAttribute(name) 獲得屬性值。
- isDisplayed() 設置該元素是否用戶可見。
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 類提供了鼠標操作的常用方法:
- contextClick() 右擊
- clickAndHold() 鼠標點擊並控制
- doubleClick() 雙擊
- dragAndDrop() 拖動
- release() 釋放鼠標
- perform() 執行所有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();
}
}
- import org.openqa.selenium.interactions.Actions;
導入提供鼠標操作的 ActionChains 類
- Actions(driver) 調用Actions()類,將瀏覽器驅動driver作爲參數傳入。
- clickAndHold() 方法用於模擬鼠標懸停操作, 在調用時需要指定元素定位。
- perform() 執行所有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();
}
}
需要說明的是,上面的腳本沒有什麼實際意義,但向我們展示了模擬鍵盤各種按鍵與組合鍵的用法。
- 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() 獲取頁面文本信息。
下面同樣以百度爲例,介紹如何獲取這些信息。
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提供了兩種類型的等待:顯式等待和隱式等待。
1.顯示等待
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。
2.隱式等待
WebDriver 提供了幾種方法來等待元素。
- implicitlyWait。識別對象時的超時時間。過了這個時間如果對象還沒找到的話就會拋出NoSuchElement異常。
- setScriptTimeout。異步腳本的超時時間。WebDriver可以異步執行腳本,這個是設置異步執行腳本腳本返回結果的超時時間。
- pageLoadTimeout。頁面加載時的超時時間。因爲WebDriver會等頁面加載完畢再進行後面的操作,所以如果頁面超過設置時間依然沒有加載完成,那麼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();
}
}
在本例中所涉及的新方法如下:
- getWindowHandle(): 獲得當前窗口句柄。
- getWindowHandles(): 返回的所有窗口的句柄到當前會話。
- switchTo().window(): 用於切換到相應的窗口,與上一節的switchTo().frame()類似,前者用於不同窗口的切換, 後者用於不同表單之間的切換。
十五、下拉框選擇
有時我們會碰到下拉框,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()方法符用於選取<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()方法接受這個彈窗。
接受一個警告框的代碼如下:
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是否正確, 因爲基於真實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 信息。
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]
十九、調用JavaScript代碼
雖然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圖片文件了。
其它總結
1:可以用萬能的js,只要selenium遇到的坑,都可以用js去解決。