• Selenium入门(二)Java整合Selenium实现模拟登录


    上一篇文章已经讲述了Java搭建Selenium环境:

    Selenium入门(一)Java 搭建 Selenium 环境

    下面接着实现模拟登录功能,这里拿自己的网站来进行测试,如下图

     

    这里我把验证码固定了,所以不需要输入验证码即可实现。

    实现思路

    1. 首先输入登录url,用WebDriver模拟打开登录页面
    2. 然后找到输入用户名和密码的input框
    3. 模拟填写用户名和密码
    4. 找到点击登录的按钮,模拟点击登录,这样就实现了模拟登录。
    5. 采用WebDriver中的【By.xpath】方法获取Dom元素
    6. xpath获取方式如下:

            鼠标移到输入框,右键点击【检查】,找到该元素所在位置

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

     


    代码实现

    • 主要实现代码如下:

    需要注意的是webDriver的每次响应操作都要用sleep()函数加入一个时间间隔。

    由于浏览器的渲染需要耗费一定的时间,而在程序执行时几乎是瞬间完成,所以要用sleep()函数。

    1. import com.saas.reptile.utils.Common;
    2. import com.saas.reptile.utils.LogUtils;
    3. import org.openqa.selenium.By;
    4. import org.openqa.selenium.WebDriver;
    5. import org.openqa.selenium.WebElement;
    6. import org.openqa.selenium.chrome.ChromeDriver;
    7. import org.openqa.selenium.chrome.ChromeOptions;
    8. public class TestController {
    9. public static void main(String[] args){
    10. WebDriver webDriver = null;
    11. try {
    12. // 设置 chromedirver 的存放位置
    13. System.getProperties().setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
    14. ChromeOptions chromeOptions = new ChromeOptions();
    15. chromeOptions = Common.addArguments(chromeOptions);
    16. // 实例化
    17. webDriver = new ChromeDriver(chromeOptions);
    18. // 1.模拟打开登陆页面
    19. String loginUrl = "http://192.168.1.115:8088/#/login";
    20. LogUtils.info("打开登录页面,地址是{}",loginUrl);
    21. webDriver.get(loginUrl);
    22. // 2.等3秒钟响应后再操作,不然内容可能还没有返回
    23. Thread.sleep(3000L);
    24. // xpath 输入框元素的绝对路径
    25. // 3.找到账号的输入框,并模拟输入账号
    26. WebElement accountInput = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/div[1]/div/div/input"));
    27. accountInput.sendKeys("admin");
    28. LogUtils.info("开始输入账号...");
    29. Thread.sleep(1000L);
    30. // 4.找到密码的输入框,并模拟输入密码
    31. WebElement passwordInput = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/div[2]/div/div/input"));
    32. passwordInput.sendKeys("123456");
    33. LogUtils.info("开始输入密码...");
    34. Thread.sleep(1000L);
    35. // 5.找到登陆的按钮,并模拟点击登陆
    36. WebElement loginButton = webDriver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div/form/button"));
    37. loginButton.click();
    38. LogUtils.info("开始点击登录...");
    39. Thread.sleep(3000L);
    40. doSomeThing(webDriver);
    41. } catch (Exception e) {
    42. e.printStackTrace();
    43. } finally {
    44. if (webDriver != null) {
    45. webDriver.quit();
    46. }
    47. }
    48. }
    49. }
    • Common方法如下:
    1. public class Common {
    2. /**
    3. * chrome添加参数
    4. * @param options
    5. * @return
    6. */
    7. public static ChromeOptions addArguments(ChromeOptions options){
    8. options.addArguments("disable-infobars");
    9. // 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
    10. options.addArguments("--headless");
    11. // 启动无沙盒模式运行,以最高权限运行
    12. options.addArguments("--no-sandbox");
    13. // 优化参数
    14. // 不加载图片, 提升速度
    15. options.addArguments("blink-settings=imagesEnabled=false");
    16. options.addArguments("--disable-dev-shm-usage");
    17. // 禁用gpu渲染
    18. options.addArguments("--disable-gpu");
    19. // 禁用阻止弹出窗口
    20. options.addArguments("--disable-popup-blocking");
    21. // 禁用扩展
    22. options.addArguments("disable-extensions");
    23. // 禁用JavaScript
    24. options.addArguments("--disable-javascript");
    25. // 默认浏览器检查
    26. options.addArguments("no-default-browser-check");
    27. Map<String, Object> prefs = new HashMap();
    28. prefs.put("credentials_enable_service", false);
    29. prefs.put("profile.password_manager_enabled", false);
    30. // 禁用保存密码提示框
    31. options.setExperimentalOption("prefs", prefs);
    32. return options;
    33. }
    34. }
    • LogUtils.class文件如下:
    1. public class LogUtils {
    2. private static final org.apache.commons.logging.Log logger;
    3. private static final Object lock = new Object();
    4. static {
    5. synchronized (lock) {
    6. logger = LogFactory.getLog(LogUtils.class);
    7. }
    8. }
    9. public static void info(Object... msgs) {
    10. StringBuilder stringBuilder = new StringBuilder();
    11. Throwable e = null;
    12. for (Object msg : msgs) {
    13. if (msg != null) {
    14. if (msg instanceof Throwable) {
    15. e = (Throwable) msg;
    16. } else {
    17. stringBuilder.append(msg).append(" ");
    18. }
    19. }
    20. }
    21. logger.info(stringBuilder, e);
    22. }
    23. public static void error(Object... msgs) {
    24. StringBuilder stringBuilder = new StringBuilder();
    25. Throwable e = null;
    26. for (Object msg : msgs) {
    27. if (msg != null) {
    28. if (msg instanceof Throwable) {
    29. e = (Throwable) msg;
    30. } else {
    31. stringBuilder.append(msg).append(" ");
    32. }
    33. }
    34. }
    35. logger.error(stringBuilder, e);
    36. }
    37. public static void warn(Object... msgs) {
    38. StringBuilder stringBuilder = new StringBuilder();
    39. Throwable e = null;
    40. for (Object msg : msgs) {
    41. if (msg != null) {
    42. if (msg instanceof Throwable) {
    43. e = (Throwable) msg;
    44. } else {
    45. stringBuilder.append(msg).append(" ");
    46. }
    47. }
    48. }
    49. logger.warn(stringBuilder, e);
    50. }
    51. public static void debug(Object... msgs) {
    52. StringBuilder stringBuilder = new StringBuilder();
    53. Throwable e = null;
    54. for (Object msg : msgs) {
    55. if (msg != null) {
    56. if (msg instanceof Throwable) {
    57. e = (Throwable) msg;
    58. } else {
    59. stringBuilder.append(msg).append(" ");
    60. }
    61. }
    62. }
    63. logger.debug(stringBuilder, e);
    64. }
    65. }

    获取LocalStorage里的值

     上图我们可以看到登录后的【Local Storage】和【Session Storage】的内容。

    查看org.openqa.selenium.html5.WebStorage的源码如下:

    1. package org.openqa.selenium.html5;
    2. public interface WebStorage {
    3. LocalStorage getLocalStorage();
    4. SessionStorage getSessionStorage();
    5. }

    可以看到实现了LocalStorage和SessionStorage,所以获取LocalStorage和SessionStorage里的值方法如下:

    1. public static void doSomeThing(WebDriver webDriver){
    2. // 获得LocalStorge里的数据
    3. WebStorage webStorage = (WebStorage) new Augmenter().augment(webDriver);
    4. LocalStorage localStorage = webStorage.getLocalStorage();
    5. String username = localStorage.getItem("username");
    6. System.out.println("username:" + username);
    7. // 获得SessionStorge里的数据
    8. SessionStorage sessionStorage = webStorage.getSessionStorage();
    9. String vuex = sessionStorage.getItem("vuex");
    10. System.out.println("vuex:" + vuex);
    11. }

    获取cookie

    1. public static void doSomeThing(WebDriver webDriver){
    2. // 获取cookie
    3. Set<Cookie> coo = webDriver.manage().getCookies();
    4. String cookies = "";
    5. if (coo != null){
    6. for ( Cookie cookie: coo){
    7. String name = cookie.getName();
    8. String value = cookie.getValue();
    9. cookies += name + "=" + value + "; ";
    10. }
    11. }
    12. System.out.println("cookies:" + cookies);
    13. }

    至此功能实现。

  • 相关阅读:
    Java多态之动态绑定机制
    基于风险的漏洞管理实现高效安全
    治理污染要从有效防护开始,PM2.5在线监测系统
    大数据ClickHouse(五):数据库引擎介绍与实例演示
    juddi实验过程
    Android 10.0 关于在系统Launcher3中调用截图api总是返回null的解决方案
    stream流
    C++11(一)
    【Ubuntu】Systemctl控制nacos启动与关闭
    Reflex WMS中阶系列7:已经完成拣货尚未Load的HD如果要取消拣货,该如何处理?
  • 原文地址:https://blog.csdn.net/qq_37634156/article/details/125492861