詳解介紹Selenium經常使用API的使用--Java語言(完整版)

(一)環境安裝之Java

1.安裝java

點擊 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 命令能夠運行 class 文件字節碼。
  • javac 命令能夠將 Java 源文件編譯爲 class 字節碼文件。

能讀者當前下載的 Java 版本與本書不一樣, 但安裝方法是同樣的。shell

(二)環境安裝之IntelliJ IDEA

1.安裝IntelliJ IDEA

你可能會問,爲何不用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」。

  • Project name: 項目名稱。
  • Project location: 項目在硬盤上的路徑。

點擊」Finish」結束項目建立完成。

2.編寫Hello World!

首先,打開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

1.經過jar包安裝

點擊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包添加成功。

2.經過Maven安裝

關於Maven安裝又是另外一個話題了。你能夠參考其它資料學習在IntelliJ IDEA建立Maven項目。

Maven官網idea & maven helpMaven倉庫

打開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越好!由於它會讓的第三方包管理變得很是簡單。

3.Hello Selenium

最後,少不了要寫一個簡單的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瀏覽器驅動。

(四)selenium3 瀏覽器驅動

1.下載瀏覽器驅動

當selenium升級到3.0以後,對不一樣的瀏覽器驅動進行了規範。若是想使用selenium驅動不一樣的瀏覽器,必須單獨下載並設置不一樣的瀏覽器驅動。
各瀏覽器下載地址:

2.設置瀏覽器驅動

設置瀏覽器的地址很是簡單。 咱們能夠手動建立一個存放瀏覽器驅動的目錄,如: C:\driver , 將下載的瀏覽器驅動文件(例如:chromedriver、geckodriver)丟到該目錄下。
個人電腦–>屬性–>系統設置–>高級–>環境變量–>系統變量–>Path,將「C:\driver」目錄添加到Path的值中。

3.驗證瀏覽器驅動

驗證不一樣的瀏覽器驅動是否正常使用。

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元素定位

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種寫法,這裏列幾個經常使用寫法:
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()方法符用於選取標籤的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圖片文件了。

相關文章
相關標籤/搜索