此文較長(zhǎng),我比較討厭寫的七零八落的博文痛垛,所以這里是對(duì)本人學(xué)習(xí)selenium的一個(gè)整合草慧,首先會(huì)介紹一下Selenium + Java環(huán)境搭建,接著會(huì)通過(guò)代碼對(duì)Selenium Java中常用API用法以及注意事項(xiàng)進(jìn)行說(shuō)明匙头,ok漫谷,let's start.
準(zhǔn)備工作
Java環(huán)境-JDK
·JDK的安裝網(wǎng)上教程一大堆,就不說(shuō)了
IDE-IntelliJ IDEA
·IntelliJ IDEA是本人用過(guò)的IDE里比較好用的一款蹂析,推薦一下
Selenium-jar
·Selenium舔示,下載完了以后會(huì)有一個(gè)jar包,找個(gè)地方放好
maven安裝
·maven安裝是非常簡(jiǎn)單的电抚,可以參考:
·for windows
·for mac
好用的瀏覽器
·推薦Chrome惕稻,下載地址就百度吧
瀏覽器驅(qū)動(dòng)
·如果是用的Chrome,到這里對(duì)應(yīng)關(guān)系及驅(qū)動(dòng)下載找
·注意配置環(huán)境變量
搭建環(huán)境
打開IDE蝙叛,新建一個(gè)工程
Project name: 項(xiàng)目名稱
Project location: 項(xiàng)目在硬盤上的路徑
接下來(lái):
1)右鍵左側(cè)項(xiàng)目列表 src—>New —> Package 彈出窗口俺祠, 輸入包的名:javaBase
2)右鍵左側(cè)創(chuàng)建的包名:java —>New —> Java Class 彈出窗口, 輸入類的名:HelloSelenium
在HelloSelenium.java中編寫第一個(gè)java文件
package com.java.base;
public class HelloSelenium {
public static void main(String[] args){
System.out.println("hello Selenium");
}
}
運(yùn)行一下借帘,看下是不是能正常拋出 hello Selenium
ok蜘渣,一切正常,接下來(lái)我們導(dǎo)入Selenuim-jar包:
點(diǎn)擊菜單欄 File –> Project Structure(快捷鍵Ctrl + Alt + Shift + s) 肺然,點(diǎn)擊 Project Structure界面左側(cè) 的“Modules” 蔫缸。在“Dependencies” 標(biāo)簽界面下,點(diǎn)擊右邊綠色的“+” 號(hào)狰挡,選擇第一個(gè)選項(xiàng)“JARs or directories…” 捂龄,選擇相應(yīng)的 jar 包,點(diǎn)“OK” 加叁,jar包添加成功
如果我們剛才新建的是一個(gè)java項(xiàng)目倦沧,我們需要把它轉(zhuǎn)換成一個(gè)maven工程
很簡(jiǎn)單,項(xiàng)目上右鍵點(diǎn)擊 Add Framework Support它匕,然后勾選Maven展融,點(diǎn)擊ok
接下來(lái)我們打開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>
點(diǎn)擊彈框中的 import Changes
接下來(lái)我們寫一個(gè)Demo來(lái)驗(yàn)證一下,新建一個(gè) SeleniumTest類
package javaBase;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://www.baidu.com");
String title = driver.getTitle();
System.out.printf(title);
driver.close();
}
}
到這里豫柬,環(huán)境就搭建好了
常用API
定位元素
定位元素是最常用也最重要的API之一告希,與python類似扑浸,java中也提供了八種定位方法
·id
·name
·class name
·tag name
·link text
·partial link text
·xpath
·css selector
對(duì)應(yīng)的java代碼為
findElement(By.id())
findElement(By.name())
findElement(By.className())
findElement(By.tagName())
findElement(By.linkText())
findElement(By.partialLinkText())
findElement(By.xpath())
findElement(By.cssSelector())
關(guān)于元素定位的知識(shí)可以參考:
1.(https://saucelabs.com/resources/articles/selenium-tips-css-selectors)
2.(http://blog.csdn.net/qingchunjun/article/details/42581261)
想要了解更多可以參考:
API實(shí)例
這里我會(huì)說(shuō)到關(guān)于web自動(dòng)化的一些常用API用法及注意事項(xiàng)
包括 :
1.模擬鼠標(biāo)操作
2.模擬鍵盤操作
3.獲取斷言
4.設(shè)置元素等待
5.定位元素組
6.表單切換
7.多窗口切換
8.下拉框選擇
9.警告框處理
10.文件上傳
11.cookie操作
12.調(diào)用JavaScrip
13.窗口截圖 等
感興趣可以一一試試,參考代碼如下:
package JavaBase;
import com.sun.jna.platform.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Created by moooke on 2017/8/21.
*/
public class HelloSelenium {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("http://www.baidu.com/");
String title = driver.getTitle();
System.out.println(title);
// System.out.println("改變?yōu)g覽器窗口大小");
// Borwser(driver);
// System.out.println("瀏覽器前進(jìn)后退");
// BrowserGo(driver);
// System.out.println("瀏覽器元素操作");
// BrowserOperation(driver);
// System.out.println("模擬鼠標(biāo)操作");
// MouseOperation(driver);
// System.out.println("模擬鍵盤操作");
// KeyBoardOperation(driver);
// System.out.println("獲取斷言信息");
// Assert(driver);
// System.out.println("設(shè)置元素等待");
// ElementWait(driver);
// System.out.println("定位一組元素");
// ElementsPositioning(driver);
// System.out.println("多表單切換");
// SwitchTable(driver);
// System.out.println("多窗口切換");
// WindowsSwitch(driver);
// System.out.println("下拉框選擇");
// SelectWindow(driver);
// System.out.println("警告框處理");
// AlertDemo(driver);
// System.out.println("文件上傳");
// FileUpload(driver);
// System.out.println("瀏覽器Cookie操作");
// BorwserCookie(driver);
// System.out.println("執(zhí)行JavaScript代碼");
// JavaScript(driver);
System.out.println("獲取窗口截圖");
ScreenShot(driver);
}
//改變窗口大小
private static void Borwser(WebDriver driver) throws InterruptedException {
WebDriver driver1;
driver1 = driver;
driver1.manage().window().maximize();
Thread.sleep(2000);
// driver1.get("https://m.baidu.cn");
driver1.manage().window().setSize(new Dimension(1200,720));
Thread.sleep(2000);
driver1.quit();
}
//前進(jìn)后退
private static void BrowserGo(WebDriver driver) throws InterruptedException{
WebDriver driver2;
driver2 = driver;
//看看鏈接地址
System.out.printf("now accesss %s \n", driver.getCurrentUrl());
Thread.sleep(2000);
//點(diǎn)擊新聞鏈接
driver2.findElement(By.linkText("新聞")).click();
System.out.printf("now accesss %s \n", driver.getCurrentUrl());
Thread.sleep(1000);
//試試瀏覽器后退
driver2.navigate().back();
System.out.printf("back to %s \n", driver2.getCurrentUrl());
Thread.sleep(1000);
//試試瀏覽器往前
driver2.navigate().forward();
System.out.printf("forward to %s \n", driver2.getCurrentUrl());
Thread.sleep(1000);
//試試瀏覽器刷新
driver2.navigate().refresh();
System.out.printf("refresh broswer", driver2.getCurrentUrl());
Thread.sleep(1000);
driver2.quit();
}
//瀏覽器元素操作
private static void BrowserOperation(WebDriver driver) throws InterruptedException{
WebDriver driver3;
driver3 = driver;
WebElement search_text = driver3.findElement(By.id("kw"));
WebElement search_button = driver3.findElement(By.id("su"));
// clear() 清除文本 | sendKeys(*value) 模擬按鍵輸入
search_text.sendKeys("試一下輸入");
Thread.sleep(1000);
search_text.clear();
Thread.sleep(1000);
search_text.sendKeys("Selenium");
Thread.sleep(1000);
search_button.click();
Thread.sleep(1000);
//sendKeys()方法模擬鍵盤向輸入框里輸入內(nèi)容燕偶。我們還可以用它發(fā)送鍵盤按鍵喝噪,甚至用它來(lái)指定上傳的文件。
driver3.navigate().back();
Thread.sleep(1000);
//搜索到內(nèi)容以后我回到百度首頁(yè)指么,這時(shí)候要重新定位元素酝惧,不然會(huì)報(bào)錯(cuò)
WebElement search_text2 = driver3.findElement(By.id("kw"));
WebElement search_button2 = driver3.findElement(By.id("su"));
search_text2.sendKeys("Java");
search_text2.submit();
Thread.sleep(1000);
search_text2.submit();
Thread.sleep(1000);
//submit()方法用于提交表單。例如伯诬,在搜索框輸入關(guān)鍵字之后的“回車” 操作晚唇,就可以通過(guò) submit()方法模擬.
//getSize()
//getText()
//getAttribute(name) 獲取屬性值
//isDisplayed() 設(shè)置元素是否用戶可見
System.out.println("輸入框尺寸:" + search_text2.getSize());
System.out.println("提交按鈕尺寸:" + search_button2.getSize());
System.out.println("提交按鈕文本:" + search_button2.getText());
System.out.println("輸入框id:" + search_text2.getAttribute("id") +
" 輸入框Type:" + search_text2.getAttribute("Type"));
System.out.println("輸入框是否可見:" + search_text2.isDisplayed());
driver3.quit();
}
//鼠標(biāo)操作
/**
* 在WebDriver中,這些關(guān)于鼠標(biāo)操作的方法封裝在ActionChains類中:
* ?????
* contextClick() 右擊
* clickAndHold() 鼠標(biāo)點(diǎn)擊并控制
* doubleClick() 雙擊
* dragAndDrop() 拖動(dòng)
* release() 釋放鼠標(biāo)
* perform() 執(zhí)行所有Actions中存儲(chǔ)的行為,可以理解成是對(duì)整個(gè)操作的提交動(dòng)作
*/
private static void MouseOperation(WebDriver driver) throws InterruptedException{
WebDriver driver4;
driver4 = driver;
//找到百度首頁(yè)設(shè)置按鈕盗似,并懸停在按鈕上
WebElement search_setting = driver4.findElement(By.linkText("設(shè)置"));
Actions action = new Actions(driver4);
action.clickAndHold(search_setting).perform();
Thread.sleep(3000);
// //鼠標(biāo)右鍵點(diǎn)擊指定元素
// action.contextClick(driver4.findElement(By.id("kw"))).perform();
// action.click(driver4.findElement(By.id("kw"))).perform();
// Thread.sleep(2000);
//鼠標(biāo)雙擊指定的元素
action.doubleClick(driver4.findElement(By.id("su"))).perform();
Thread.sleep(2000);
//鼠標(biāo)拖拽動(dòng)作哩陕,將 search_setting 元素拖放到 search_text 元素的位置
WebElement search_text = driver4.findElement(By.id("kw"));
WebElement search_setting2 = driver4.findElement(By.linkText("設(shè)置"));
action.dragAndDrop(search_setting2, search_text).perform();
Thread.sleep(2000);
//釋放鼠標(biāo)
action.release().perform();
driver4.quit();
//PS:這里我發(fā)現(xiàn) search_setting 被操作以后如果我在后面的 dragAndDrop 中直接
// 使用 search_setting 會(huì)報(bào)錯(cuò),但是我重新建立一個(gè)對(duì)象就不會(huì)報(bào)錯(cuò) -..-
}
//鍵盤操作
/**
* 可以模擬鍵盤按鍵
* 以及組合鍵,例如 Ctrl+A赫舒、 Ctrl+C 等
* 鍵盤操作都放在 org.openqa.selenium.Keys 里
* ?????
* (Keys.BACK_SPACE) 回格鍵
* (Keys.SPACE) 空格鍵(Space)
* (Keys.TAB) 制表鍵(Tab)
* (Keys.ESCAPE) 回退鍵(Esc)
* (Keys.ENTER) 回車鍵(Enter)
* (Keys.F1) 鍵盤 F1
* ...
* (Keys.F12) 鍵盤 F12
*/
private static void KeyBoardOperation(WebDriver driver) throws InterruptedException{
WebDriver driver5;
driver5 = driver;
WebElement input = driver5.findElement(By.id("kw"));
//輸入下準(zhǔn)備數(shù)據(jù)
input.sendKeys("Seleniumm");
Thread.sleep(2000);
//按下刪除鍵,刪除一個(gè) "m"
input.sendKeys(Keys.BACK_SPACE);
Thread.sleep(2000);
//輸入空格鍵
input.sendKeys(Keys.SPACE);
input.sendKeys(" + Java");
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);
driver5.quit();
}
//獲取頁(yè)面元素
private static void Assert(WebDriver driver) throws InterruptedException{
WebDriver driver6;
driver6 = driver;
//獲取當(dāng)前的 title 和 url
System.out.printf("title of current page is %s\n", driver6.getTitle());
System.out.printf("url of current page is %s\n", driver6.getCurrentUrl());
//百度搜索
WebElement search = driver6.findElement(By.id("kw"));
search.sendKeys("Selenium");
search.sendKeys(Keys.ENTER);
Thread.sleep(2000);
System.out.println("======== After search ========");
//獲取當(dāng)前的 title 和 url 看看
System.out.printf("title of current page is %s\n", driver6.getTitle());
System.out.printf("url of current page is %s\n", driver6.getCurrentUrl());
Thread.sleep(2000);
//獲取第一條搜索結(jié)果的標(biāo)題
WebElement result = driver6.findElement(By.xpath("http://*[@id=\"1\"]/h3/a"));
System.out.println(result.getText());
Thread.sleep(2000);
driver6.quit();
}
//設(shè)置頁(yè)面元素等待
private static void ElementWait(WebDriver driver) throws InterruptedException{
WebDriver driver7;
driver7 = driver;
//顯示等待悍及,針對(duì)某個(gè)元素
/**
* WebDriverWait(driver, 10, 1)
* driver: 瀏覽器驅(qū)動(dòng)。 10: 最長(zhǎng)超時(shí)時(shí)間号阿, 默認(rèn)以秒為單位并鸵。 1: 檢測(cè)的的間隔(步長(zhǎng)) 時(shí)間, 默認(rèn)為 0.5s
*/
WebDriverWait wait = new WebDriverWait(driver7, 10,1);
wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver webDriver) {
return webDriver.findElement(By.id("kw"));
}
}).sendKeys("Selenium");
driver7.findElement(By.id("su")).click();
Thread.sleep(2000);
// driver7.quit();
//隱式等待
/**
* WebDriver提供的幾種方法
* 1. implicitlyWait (識(shí)別對(duì)象時(shí)的超時(shí)時(shí)間,過(guò)了這個(gè)時(shí)間如果對(duì)象還沒找到的話就會(huì)拋出NoSuchElement異常)
* 2. setScriptTimeout (異步腳本的超時(shí)時(shí)間,WebDriver可以異步執(zhí)行腳本扔涧,這個(gè)是設(shè)置異步執(zhí)行腳本腳本返回結(jié)果的超時(shí)時(shí)間)
* 3. pageLoadTimeout (頁(yè)面加載時(shí)的超時(shí)時(shí)間,因?yàn)閃ebDriver會(huì)等頁(yè)面加載完畢再進(jìn)行后面的操作,所以如果頁(yè)面超過(guò)設(shè)置時(shí)間依然沒有加載完成,那么WebDriver就會(huì)拋出異常)
*/
//頁(yè)面加載超時(shí)時(shí)間設(shè)置為 5s
driver7.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
driver7.get("https://www.baidu.com/");
//每一個(gè)隱式等待都只對(duì)下一個(gè)對(duì)應(yīng)的 driver 操作有效
driver7.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
driver7.get("https://www.google.com");
//定位對(duì)象給定 3s 的時(shí)間,如果 3s 內(nèi)沒有定位到則拋出異常
driver7.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver7.findElement(By.id("kw")).sendKeys("selenium");
Thread.sleep(2000);
//異步腳本的超時(shí)時(shí)間設(shè)置為 3s
driver7.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS);
driver7.quit();
}
//定位『一組』元素
/**
* 定位一組元素其實(shí)就類似于定位元素,只不過(guò)用的方法是 findElements ,多一個(gè) "s"
*/
private static void ElementsPositioning(WebDriver driver) throws InterruptedException {
WebDriver driver8;
driver8 = driver;
WebElement search_text = driver8.findElement(By.id("kw"));
search_text.sendKeys("Selenium");
search_text.submit();
Thread.sleep(2000);
/**
* 通過(guò) xpath ,我們找到匹配到的第一頁(yè)搜索結(jié)果 循環(huán)打印
* 這里打印的是第一頁(yè)搜索的搜索結(jié)果园担,因?yàn)樗阉鹘Y(jié)果展示都可以通過(guò) //div/div/h3 定位到
*/
List<WebElement> search_result = driver8.findElements(By.xpath("http://div/div/h3"));
//打印元素的個(gè)數(shù)
System.out.println(search_result.size());
//循環(huán)打印搜索結(jié)果的標(biāo)題
for (WebElement result : search_result){
System.out.println(result.getText());
}
System.out.println("-------- *..* --------");
//打印第 n 結(jié)果的標(biāo)題
WebElement text = search_result.get(search_result.size() - 10);
System.out.println(text.getText());
driver8.quit();
}
//多表單切換
/**
* WebDriver 只能在一個(gè)頁(yè)面上對(duì)元素識(shí)別與定位,但是對(duì)于 frame/iframe 表單內(nèi)嵌頁(yè)面上的元素?zé)o法直接定位
* 這時(shí)就需要通過(guò) switchTo().frame()方法將當(dāng)前定 位的主體切換為 frame/iframe 表單的內(nèi)嵌頁(yè)面中
* iframe 基本已經(jīng)被h5淘汰,不過(guò)我們還是要了解一下,以126郵箱登錄為例
*/
private static void SwitchTable(WebDriver driver) {
WebDriver driver9;
driver9 = driver;
driver9.get("http://www.126.com");
//這里等待 5s ,因?yàn)?iframe 的創(chuàng)建比其它包括 scripts 和 css 的 DOM 元素的創(chuàng)建要慢 1-2 個(gè)數(shù)量級(jí)
driver9.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement frame = driver9.findElement(By.xpath("http://*[@id='loginDiv']/iframe"));
driver9.switchTo().frame(frame); //switchTo 還可以切換到彈出框等
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();
//切換回默認(rèn)頁(yè)面
driver.switchTo().defaultContent();
}
//多窗口切換
/**
* getWindowHandle(): 獲得當(dāng)前窗口句柄
* getWindowHandles(): 返回的所有窗口的句柄到當(dāng)前會(huì)話
* switchTo().window(): 用于切換到相應(yīng)的窗口,與上面的switchTo().frame()類似
*/
private static void WindowsSwitch(WebDriver driver) throws InterruptedException {
WebDriver driver10;
driver10 = driver;
//獲得當(dāng)前窗口句柄
String search_handle = driver10.getWindowHandle();
//打開百度注冊(cè)窗口
driver10.findElement(By.linkText("登錄")).click();
Thread.sleep(2000);
driver10.findElement(By.linkText("立即注冊(cè)")).click();
Thread.sleep(2000);
//獲得當(dāng)前窗口的句柄
String search_handle_register = driver10.getWindowHandle();
//獲取所有窗口句柄
Set<String> handles = driver10.getWindowHandles();
//判斷是否為注冊(cè)窗口, 并操作注冊(cè)窗口上的元素
for (String handle : handles){
if (handle.equals(search_handle_register) == false){
driver10.switchTo().window(handle);
System.out.println("現(xiàn)在在注冊(cè)頁(yè)面");
Thread.sleep(2000);
driver10.findElement(By.name("userName")).clear();
driver.findElement(By.name("userName")).sendKeys("用戶名");
driver.findElement(By.name("phone")).clear();
driver.findElement(By.name("phone")).sendKeys("電話號(hào)碼");
//......
Thread.sleep(2000);
//關(guān)閉當(dāng)前窗口
driver10.close();
}
}
Thread.sleep(2000);
driver10.quit();
}
//下拉框選擇
/**
* WebDriver提供了 Select 類來(lái)處理下拉框
* Select類用于定位<select>標(biāo)簽枯夜。selectByValue()方法符用于選取<option>標(biāo)簽的value值
*/
private static void SelectWindow(WebDriver driver) throws InterruptedException {
WebDriver driver11;
driver11 = driver;
//以百度搜索設(shè)置頁(yè)面的下拉框?yàn)槔? driver11.findElement(By.linkText("設(shè)置")).click();
driver11.findElement(By.linkText("搜索設(shè)置")).click();
Thread.sleep(2000);
//<select>標(biāo)簽的下拉框選擇
WebElement el = driver11.findElement(By.xpath("http://select"));
Select sel = new Select(el);
sel.selectByValue("20");
Thread.sleep(2000);
driver11.quit();
}
//警告框處理
/**
* 在WebDriver中處理JavaScript所生成的alert弯汰、confirm以及prompt
* 1. 使用switchTo().alert()方法定位到alert/confirm/prompt
* 2. 使用text/accept/dismiss/sendKeys等方法進(jìn)行操作
* -----------------------------------------------
* getText(): 返回 alert/confirm/prompt 中的文字信息
* accept(): 接受現(xiàn)有警告框
* dismiss(): 解散現(xiàn)有警告框
* sendKeys(keysToSend): 發(fā)送文本至警告框
* keysToSend: 將文本發(fā)送至警告框
*/
private static void AlertDemo(WebDriver driver) throws InterruptedException {
WebDriver driver12;
driver12 = driver;
//類似百度設(shè)置的彈出框是不能通過(guò)前端工具對(duì)其進(jìn)行定位的,這時(shí)候就要用到switchTo().alert()了
driver.findElement(By.linkText("設(shè)置")).click();
driver.findElement(By.linkText("搜索設(shè)置")).click();
Thread.sleep(2000);
//點(diǎn)擊保存設(shè)置
driver12.findElement(By.linkText("保存設(shè)置")).click();
System.out.println(driver12.switchTo().alert().getText());
//接收彈框
driver12.switchTo().alert().accept();
Thread.sleep(2000);
driver12.quit();
}
//文件上傳 *
/**
* 對(duì)于通過(guò)input標(biāo)簽實(shí)現(xiàn)的上傳功能,可以將其看作是一個(gè)輸入框,可通過(guò)sendKeys()指定本地文件路徑的方式實(shí)現(xiàn)文件上傳
*/
private static void FileUpload(WebDriver driver) throws InterruptedException {
WebDriver driver13;
driver13 = driver;
//找到絕對(duì)路徑
File file = new File(" ./xxx(路徑)/xxx(路徑)/文件");
String filePath = file.getAbsolutePath();
driver13.get(filePath);
//定位上傳按鈕,添加本地文件
driver13.findElement(By.name("file")).sendKeys("E:\\\\upload_file.txt");
Thread.sleep(2000);
driver13.quit();
}
//瀏覽器Cookie操作
/**
* WebDriver操作Cookie相關(guān)方法
* getCookies(): 獲得所有cookie信息
* getCookieNamed(String name): 返回字典的key為"name"的Cookie信息
* addCookie(cookie dict): 添加Cookie, "cookie dict"指字典對(duì)象,必須有 name和 value值
* deleteCookieNamed(String name): 刪除Cookie信息, "name"是要?jiǎng)h除的 cookie的名稱; "optionsString"是該Cookie 的選項(xiàng), 目前支持"路徑"湖雹、"域"
* deleteAllCookies(): 刪除所有的cookie 信息
*/
private static void BorwserCookie(WebDriver driver) {
WebDriver driver14;
driver14 = driver;
Cookie cookie1 = new Cookie("name", "key-aaaaa");
Cookie cookie2 = new Cookie("value", "value-bbbbb");
driver14.manage().addCookie(cookie1);
driver14.manage().addCookie(cookie2);
//獲得 Cookie
Set<Cookie> cookies = driver14.manage().getCookies();
System.out.println(cookies);
//刪除所有 cookie
//driver.manage().deleteAllCookies();
driver14.quit();
}
//調(diào)用JavaScript代碼
/**
* WebDriver提供了 executeScript()方法來(lái)執(zhí)行 JavaScript代碼
* 以調(diào)整瀏覽器滾動(dòng)條位置為例
*/
private static void JavaScript(WebDriver driver) throws InterruptedException {
WebDriver driver15;
driver15 = driver;
//設(shè)置瀏覽器窗口大小
driver15.manage().window().setSize(new Dimension(700, 600));
Thread.sleep(2000);
//百度搜索
driver15.findElement(By.id("kw")).sendKeys("Selenium");
driver15.findElement(By.id("su")).click();
Thread.sleep(2000);
//將頁(yè)面滾動(dòng)條拖動(dòng)
((JavascriptExecutor)driver15).executeScript("window.scrollTo(100,410)");
Thread.sleep(200);
((JavascriptExecutor)driver15).executeScript("window.scrollTo(100,420)");
Thread.sleep(200);
((JavascriptExecutor)driver15).executeScript("window.scrollTo(100,430)");
Thread.sleep(200);
((JavascriptExecutor)driver15).executeScript("window.scrollTo(100,440)");
Thread.sleep(200);
((JavascriptExecutor)driver15).executeScript("window.scrollTo(100,450)");
Thread.sleep(200);
driver15.quit();
}
//窗口截圖
private static void ScreenShot(WebDriver driver) {
WebDriver driver16;
driver16 = driver;
File srcFile = ((TakesScreenshot)driver16).getScreenshotAs(OutputType.FILE);
try {
org.apache.commons.io.FileUtils.copyFile(srcFile, new File("/Users/moooke/screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
driver16.quit();
}
}
熟練掌握使用這些API已經(jīng)能滿足基本的日常測(cè)試任務(wù)咏闪,更多細(xì)節(jié)沒有一一展開說(shuō)明
關(guān)于進(jìn)階內(nèi)容后面會(huì)跟大家分享
希望本文能給有需要的朋友帶來(lái)一點(diǎn)幫助,謝謝~