上一篇文章已经讲述了Java搭建Selenium环境:
Selenium入门(一)Java 搭建 Selenium 环境
下面接着实现模拟登录功能,这里拿自己的网站来进行测试,如下图
这里我把验证码固定了,所以不需要输入验证码即可实现。
鼠标移到输入框,右键点击【检查】,找到该元素所在位置

然后右键,选择【复制】,再选择【Copy full XPath】,即可得到xpath。

需要注意的是webDriver的每次响应操作都要用sleep()函数加入一个时间间隔。
由于浏览器的渲染需要耗费一定的时间,而在程序执行时几乎是瞬间完成,所以要用sleep()函数。
- 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 {
- // 设置 chromedirver 的存放位置
- System.getProperties().setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
- ChromeOptions chromeOptions = new ChromeOptions();
- chromeOptions = Common.addArguments(chromeOptions);
- // 实例化
- webDriver = new ChromeDriver(chromeOptions);
- // 1.模拟打开登陆页面
- String loginUrl = "http://192.168.1.115:8088/#/login";
- LogUtils.info("打开登录页面,地址是{}",loginUrl);
- webDriver.get(loginUrl);
- // 2.等3秒钟响应后再操作,不然内容可能还没有返回
- 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.找到登陆的按钮,并模拟点击登陆
- WebElement loginButton = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/button"));
- loginButton.click();
- LogUtils.info("开始点击登录...");
- Thread.sleep(3000L);
-
- doSomeThing(webDriver);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (webDriver != null) {
- webDriver.quit();
- }
- }
- }
- }
- public class Common {
-
-
- /**
- * chrome添加参数
- * @param options
- * @return
- */
- public static ChromeOptions addArguments(ChromeOptions options){
- options.addArguments("disable-infobars");
- // 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
- options.addArguments("--headless");
- // 启动无沙盒模式运行,以最高权限运行
- options.addArguments("--no-sandbox");
-
- // 优化参数
- // 不加载图片, 提升速度
- options.addArguments("blink-settings=imagesEnabled=false");
- options.addArguments("--disable-dev-shm-usage");
- // 禁用gpu渲染
- options.addArguments("--disable-gpu");
-
- // 禁用阻止弹出窗口
- options.addArguments("--disable-popup-blocking");
- // 禁用扩展
- options.addArguments("disable-extensions");
- // 禁用JavaScript
- options.addArguments("--disable-javascript");
- // 默认浏览器检查
- 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;
- }
- }
- 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);
- }
- }

上图我们可以看到登录后的【Local Storage】和【Session Storage】的内容。
查看org.openqa.selenium.html5.WebStorage的源码如下:
- package org.openqa.selenium.html5;
-
- public interface WebStorage {
- LocalStorage getLocalStorage();
-
- SessionStorage getSessionStorage();
- }
可以看到实现了LocalStorage和SessionStorage,所以获取LocalStorage和SessionStorage里的值方法如下:
- public static void doSomeThing(WebDriver webDriver){
- // 获得LocalStorge里的数据
- WebStorage webStorage = (WebStorage) new Augmenter().augment(webDriver);
- LocalStorage localStorage = webStorage.getLocalStorage();
- String username = localStorage.getItem("username");
- System.out.println("username:" + username);
- // 获得SessionStorge里的数据
- SessionStorage sessionStorage = webStorage.getSessionStorage();
- String vuex = sessionStorage.getItem("vuex");
- System.out.println("vuex:" + vuex);
-
- }
- 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);
- }
至此功能实现。