上一篇文章已經(jīng)講述了Java搭建Selenium環(huán)境:
Selenium入門(一)Java 搭建 Selenium 環(huán)境
下面接著實(shí)現(xiàn)模擬登錄功能,這里拿自己的網(wǎng)站來進(jìn)行測試,如下圖
?
這里我把驗(yàn)證碼固定了,所以不需要輸入驗(yàn)證碼即可實(shí)現(xiàn)。
實(shí)現(xiàn)思路
- 首先輸入登錄url,用WebDriver模擬打開登錄頁面
- 然后找到輸入用戶名和密碼的input框
- 模擬填寫用戶名和密碼
- 找到點(diǎn)擊登錄的按鈕,模擬點(diǎn)擊登錄,這樣就實(shí)現(xiàn)了模擬登錄。
- 采用WebDriver中的【By.xpath】方法獲取Dom元素
- xpath獲取方式如下:
? ? ? ? 鼠標(biāo)移到輸入框,右鍵點(diǎn)擊【檢查】,找到該元素所在位置
?然后右鍵,選擇【復(fù)制】,再選擇【Copy full XPath】,即可得到xpath。
?
代碼實(shí)現(xiàn)
- 主要實(shí)現(xiàn)代碼如下:
需要注意的是webDriver的每次響應(yīng)操作都要用sleep()函數(shù)加入一個(gè)時(shí)間間隔。
由于瀏覽器的渲染需要耗費(fèi)一定的時(shí)間,而在程序執(zhí)行時(shí)幾乎是瞬間完成,所以要用sleep()函數(shù)。
import com.saas.reptile.utils.Common;
import com.saas.reptile.utils.LogUtils;
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.chrome.ChromeOptions;
public class TestController {
public static void main(String[] args){
WebDriver webDriver = null;
try {
// 設(shè)置 chromedirver 的存放位置
System.getProperties().setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions = Common.addArguments(chromeOptions);
// 實(shí)例化
webDriver = new ChromeDriver(chromeOptions);
// 1.模擬打開登陸頁面
String loginUrl = "http://192.168.1.115:8088/#/login";
LogUtils.info("打開登錄頁面,地址是{}",loginUrl);
webDriver.get(loginUrl);
// 2.等3秒鐘響應(yīng)后再操作,不然內(nèi)容可能還沒有返回
Thread.sleep(3000L);
// xpath 輸入框元素的絕對路徑
// 3.找到賬號的輸入框,并模擬輸入賬號
WebElement accountInput = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/div[1]/div/div/input"));
accountInput.sendKeys("admin");
LogUtils.info("開始輸入賬號...");
Thread.sleep(1000L);
// 4.找到密碼的輸入框,并模擬輸入密碼
WebElement passwordInput = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/div[2]/div/div/input"));
passwordInput.sendKeys("123456");
LogUtils.info("開始輸入密碼...");
Thread.sleep(1000L);
// 5.找到登陸的按鈕,并模擬點(diǎn)擊登陸
WebElement loginButton = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/button"));
loginButton.click();
LogUtils.info("開始點(diǎn)擊登錄...");
Thread.sleep(3000L);
doSomeThing(webDriver);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (webDriver != null) {
webDriver.quit();
}
}
}
}
- Common方法如下:
public class Common {
/**
* chrome添加參數(shù)
* @param options
* @return
*/
public static ChromeOptions addArguments(ChromeOptions options){
options.addArguments("disable-infobars");
// 瀏覽器不提供可視化頁面. linux下如果系統(tǒng)不支持可視化不加這條會啟動失敗
options.addArguments("--headless");
// 啟動無沙盒模式運(yùn)行,以最高權(quán)限運(yùn)行
options.addArguments("--no-sandbox");
// 優(yōu)化參數(shù)
// 不加載圖片, 提升速度
options.addArguments("blink-settings=imagesEnabled=false");
options.addArguments("--disable-dev-shm-usage");
// 禁用gpu渲染
options.addArguments("--disable-gpu");
// 禁用阻止彈出窗口
options.addArguments("--disable-popup-blocking");
// 禁用擴(kuò)展
options.addArguments("disable-extensions");
// 禁用JavaScript
options.addArguments("--disable-javascript");
// 默認(rèn)瀏覽器檢查
options.addArguments("no-default-browser-check");
Map<String, Object> prefs = new HashMap();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
// 禁用保存密碼提示框
options.setExperimentalOption("prefs", prefs);
return options;
}
}
- LogUtils.class文件如下:
public class LogUtils {
private static final org.apache.commons.logging.Log logger;
private static final Object lock = new Object();
static {
synchronized (lock) {
logger = LogFactory.getLog(LogUtils.class);
}
}
public static void info(Object... msgs) {
StringBuilder stringBuilder = new StringBuilder();
Throwable e = null;
for (Object msg : msgs) {
if (msg != null) {
if (msg instanceof Throwable) {
e = (Throwable) msg;
} else {
stringBuilder.append(msg).append(" ");
}
}
}
logger.info(stringBuilder, e);
}
public static void error(Object... msgs) {
StringBuilder stringBuilder = new StringBuilder();
Throwable e = null;
for (Object msg : msgs) {
if (msg != null) {
if (msg instanceof Throwable) {
e = (Throwable) msg;
} else {
stringBuilder.append(msg).append(" ");
}
}
}
logger.error(stringBuilder, e);
}
public static void warn(Object... msgs) {
StringBuilder stringBuilder = new StringBuilder();
Throwable e = null;
for (Object msg : msgs) {
if (msg != null) {
if (msg instanceof Throwable) {
e = (Throwable) msg;
} else {
stringBuilder.append(msg).append(" ");
}
}
}
logger.warn(stringBuilder, e);
}
public static void debug(Object... msgs) {
StringBuilder stringBuilder = new StringBuilder();
Throwable e = null;
for (Object msg : msgs) {
if (msg != null) {
if (msg instanceof Throwable) {
e = (Throwable) msg;
} else {
stringBuilder.append(msg).append(" ");
}
}
}
logger.debug(stringBuilder, e);
}
}
獲取LocalStorage里的值
?上圖我們可以看到登錄后的【Local Storage】和【Session Storage】的內(nèi)容。
查看org.openqa.selenium.html5.WebStorage的源碼如下:
package org.openqa.selenium.html5;
public interface WebStorage {
LocalStorage getLocalStorage();
SessionStorage getSessionStorage();
}
可以看到實(shí)現(xiàn)了LocalStorage和SessionStorage,所以獲取LocalStorage和SessionStorage里的值方法如下:文章來源:http://www.zghlxwxcb.cn/news/detail-402877.html
public static void doSomeThing(WebDriver webDriver){
// 獲得LocalStorge里的數(shù)據(jù)
WebStorage webStorage = (WebStorage) new Augmenter().augment(webDriver);
LocalStorage localStorage = webStorage.getLocalStorage();
String username = localStorage.getItem("username");
System.out.println("username:" + username);
// 獲得SessionStorge里的數(shù)據(jù)
SessionStorage sessionStorage = webStorage.getSessionStorage();
String vuex = sessionStorage.getItem("vuex");
System.out.println("vuex:" + vuex);
}
獲取cookie
public static void doSomeThing(WebDriver webDriver){
// 獲取cookie
Set<Cookie> coo = webDriver.manage().getCookies();
String cookies = "";
if (coo != null){
for ( Cookie cookie: coo){
String name = cookie.getName();
String value = cookie.getValue();
cookies += name + "=" + value + "; ";
}
}
System.out.println("cookies:" + cookies);
}
至此功能實(shí)現(xiàn)。文章來源地址http://www.zghlxwxcb.cn/news/detail-402877.html
到了這里,關(guān)于Selenium入門(二)Java整合Selenium實(shí)現(xiàn)模擬登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!