zoukankan      html  css  js  c++  java
  • Java Selenium3 WebDriver启动火狐、Chrome、IE,Edge浏览器的方法(一)

    selenium3和selenium2没有太大的区别,就是精简了一些不用的东西,对浏览器的支持更好了,比如对高版本的浏览器(FireFox,Chrome,Edge等)可以完美的支持,不用受限于版本的问题

    下面总结一下启动常用浏览器的方法

    前提

    1. 安装好java的环境配置

    2. 新建一个maven工程
      在maven的pom文件加入selenium的依赖包(版本可根据需要自行变更)
      <dependencies> <!-- selenium的驱动--> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.14.0</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8.21</version> </dependency> </dependencies>

    一、火狐浏览器

    1. 选择对应的Mozilla GeckoDriver,下载地址:https://github.com/mozilla/geckodriver/releases

    2. 把压缩包里的exe文件放到java项目中,这里用0.27.0版本的

    3. 火狐浏览器的版本>=65版本

    4. 启动火狐浏览器

      • 方式1:直接启动浏览器
    public class OpenBrower {
        
        private static String browerPath=OpenBrower.class.getResource("/files").getPath();
        @Test
        public  void openFireFox() throws IOException {
            System.out.println("start seleniium firefox");
            //设置FirefoxDriver路径
            System.setProperty("webdriver.gecko.driver",browerPath+"/geckodriver.exe");
     
            //初始化firefox浏览器实例
            WebDriver driver=new FirefoxDriver();
            //打开一个站点
            driver.get("https://www.baidu.com/");
            //设置隐形等待时间
            driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
            //窗口最大化
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
            //关闭浏览器
            driver.close();
        }
    }
    
    • 方式2:通过指定profile启动浏览器

    这样启动的好处:带着自己配置好的浏览器设置;查看profile的方法如下

    WIN+R快捷键

    如果不知道哪个是默认的,点击启动firefox按钮查看即可,也可以新建profile一个

    代码如下:

     @Test
        public void openFireFox_default() throws Exception {
     
            System.setProperty("webdriver.gecko.driver", browerPath + "/geckodriver.exe");
     
            //启动带插件的火狐浏览器
            ProfilesIni pi=new ProfilesIni();
            //default-release用户配置文件名
            FirefoxProfile profile = pi.getProfile("default-release");
     
            FirefoxOptions options = new FirefoxOptions();
            options.setProfile(profile);
     
            //初始化firefox浏览器实例
            WebDriver driver = new FirefoxDriver(options);
     
            //打开一个站点
            driver.get("https://www.jd.com/");
            //设置隐形等待时间
            Thread.sleep(3000);
            //窗口最大化
            driver.manage().window().maximize();
             Thread.sleep(3000);
            //关闭浏览器
            driver.close();
        }
    

    selenium3后之前2版本的启动方式不一样

    二、Chrome浏览器

    1. 选择对应Google Chrome Driver 下载地址:http://chromedriver.storage.googleapis.com/index.html

    2. 把压缩包里的exe文件放到java的目录里

    3. 启动浏览器

     @Test
        public void openChrome() throws Exception {
     
            //System.setProperty("webdriver.chrome.driver", browerPath + "/chromedriver.exe");
            System.setProperty("webdriver.chrome.driver", browerPath + "/chromedriver.exe");
     
            //初始化Chrome浏览器实例
            WebDriver driver = new ChromeDriver();
     
            //打开一个站点
            driver.get("https://www.baidu.com/");
     
            // 设置隐形等待时间
            Thread.sleep(5000);
            //窗口最大化
            driver.manage().window().maximize();
            Thread.sleep(5000);
            //关闭浏览器
            driver.close();
     
        }
    

    三、IE浏览器

    1. 选择对应的IE Driver,下载地址:https://selenium-release.storage.googleapis.com/index.html

    2. 把压缩包里的exe文件放到java的目录里

    3. 启动IE时,需要关闭如下图4个区域的保护模式:

    1. 启动浏览器
        @Test
        public void openIE() throws Exception {
            System.setProperty("webdriver.ie.driver", browerPath + "/IEDriverServer.exe");
     
            //初始化浏览器实例
            WebDriver driver = new InternetExplorerDriver();
     
            //打开一个站点
            driver.get("https://www.jd.com/");
     
            // 设置隐形等待时间
            Thread.sleep(3000);
            //窗口最大化
            driver.manage().window().maximize();
            Thread.sleep(3000);
            //关闭浏览器
            driver.close();
        }
    

    四、Edge

    1. 选择对应的Edge Driver,下载地址:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

    2. 把压缩包里的exe文件放到java的目录里

    3. 如果Edge的版本比较低,先要升级版本

    4. 代码

    @Test
        public void openEdge() throws Exception {
            System.setProperty("webdriver.edge.driver", browerPath + "/msedgedriver.exe");
     
            //初始化Chrome浏览器实例
            WebDriver driver = new EdgeDriver();
     
            //打开一个站点
            driver.get("https://www.jd.com/");
     
            // 设置隐形等待时间
            Thread.sleep(3000);
            //窗口最大化
            driver.manage().window().maximize();
            Thread.sleep(3000);
            //关闭浏览器
            driver.close();
        }
    

    备注

    1、selenium1.0还是 seleniumRC的时候,需要启动selenium-server-standalone包,用来做server。selenium RC通过server来给code和broswer建立通道,同时,该jar包包括我们用得所有的方法。
    2、在新版的selenium中,即selenium2.0-webdriver以后,不需要这个selenium-server-standalone这个包了。WebDriver api 会直接和浏览器的native交互,现在我们用selenium-java.jar包来替代。
    3、如果使用selenium-grid或者要在远程机器上的浏览器上运行用例,那么就需要selenium-server和selenium-java配合
    注:其实selenium-java就是client,他可以和本地浏览器直接交互(通过各个浏览器自身提供的driver)。同时,通过selenium-server,这个client也可以在远程机器的浏览器进行交互。

    使用配置文件控制浏览器的完整代码如下

    1. 新建一个maven项目

    1. pom文件添加依赖
    <dependencies>
            <!-- selenium的驱动-->
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>3.14.0</version>
            </dependency>
            <dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>6.8.21</version>
            </dependency>
        </dependencies>
    

    创建工具类

    1. Base类

    代码

    package selenium.framework.demo.util;
     
    /**
     * 初始化基础类
     */
    public class Base {
        //初始化InitProperties配置文件类
        static{
            new InitProperties();
        }
        public static void delay(int time) {
            try {
                Thread.sleep(time*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    1. InitProperties类

    代码:

    package selenium.framework.demo.util;
     
    import org.testng.annotations.Test;
     
    import java.io.*;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
     
    /**
     * 初始化配置类
     */
    public class InitProperties {
        //配置文件的路径
        public static final String PFILEPATH = File.separatorChar + "config" + File.separatorChar + "CONFIG.properties";
        private InputStreamReader fn = null;
        private InputStream in = null;
        private Properties config = new Properties();
        public static Map<String, String> mapproperties = new HashMap<String, String>();
     
        public InitProperties() {
            //构造初始配置文件
            init();
        }
     
        /**
         * 初始化Property配置文件,放入系统属性变量中
         */
        private void init() {
            Logger.Defaultlog("初始化配置文件");
            try {
                //调用 对象的getClass()方法是获得对象当前的类类型
                in = getClass().getClassLoader().getResourceAsStream(PFILEPATH);
                config.load(new InputStreamReader(in, "utf-8"));
     
                System.out.println(config.getProperty("WebDriver.Browser.Location"));
     
                if (!config.isEmpty()) {
                    Set<Object> keys = config.keySet();
                    for (Object key : keys) {
                        InitProperties.mapproperties.put(key.toString(), config.getProperty(key.toString()));
                        //系统参数不包含指定的键名且配置文件的键值不为空
                        if (!System.getProperties().containsKey(key.toString()) && !config.getProperty(key.toString()).isEmpty()) {
                            //置指定键对值的系统属性
                            System.setProperty(key.toString(), config.getProperty(key.toString()));
                        }
                    }
                    keys.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    //fn.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
     
        // }
     
        /**
         * 对外调试使用
         */
        public static void showAllSystemProperties() {
            Set<String> syskeys = InitProperties.mapproperties.keySet();
            for (Object key : syskeys) {
                if (System.getProperties().containsKey(key)) {
                    System.out.println(key.toString() + "  " + System.getProperty(key.toString()));
                }
            }
            syskeys.clear();
        }
    }
    
    1. WebDriverPlus类

    代码:

    package selenium.fromework.demo.webdriver;
     
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.support.events.EventFiringWebDriver;
     
    /**
     * WebDriver扩展类
     */
    public class WebDriverPlus extends EventFiringWebDriver{
        
        public WebDriverPlus(WebDriver driver) {
            super(driver);
        }
    }
    
    1. Logger类

    代码

    package selenium.fromework.demo.util;
     
    import org.testng.Reporter;
     
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    /**
     * 日志
     */
    public class Logger {
        //日期格式
        private static final DateFormat DATE_FORMAT=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //日志开关
        public static boolean isLog=true;
        //框架默认日志开关
        public static boolean isDefault=true;
        //控制台输出开关
        public static boolean isToStandardOut=true;
        //日志格式开关
        public static boolean isFormat=true;
        //命令行信息打印等级(1-5)
        public static int verbose=1;
     
        /**
         * 日志输出的相关信息
         * @param s
         * @param level
         * @param logToStandardOut
         */
        public static void log(String s,int level,boolean logToStandardOut){
            if(isLog){
                Reporter.log(logPrefix(s),level,logToStandardOut);
            }
        }
     
        public static void log(String s){
            log(s,verbose,isToStandardOut);
        }
        public static void log(String s,int level){
            log(s,verbose,isToStandardOut);
        }
        public static void log(String s,boolean logToStandardOut){
            log(s,verbose,logToStandardOut);
        }
     
        /**
         * 默认日志
         * @param s 日志输出信息
         */
        public static void Defaultlog(String s){
            if(isLog&&isDefault){
                Reporter.log(logPrefix(s),verbose,isToStandardOut);
            }
        }
     
        /**
         * 日志前缀
         * @param s
         * @return
         */
        private static String logPrefix(String s) {
            Date logtime = new Date();
            if(isFormat) {
                return "[" + System.getProperty("Project.Name", "liang") + " "+ DATE_FORMAT.format(logtime) + "] " + s;
            }
            return s;
        }
     
        /**
         * 对日志开关的操作
         */
        public static void setLog(){
            //获得properties 配置文件Logger的值,如果是false
            if(System.getProperty("Logger","true").equalsIgnoreCase("false")){
                //关闭日志开关
                Logger.isLog=false;
            }
            //Logger.StandardOut的值,如果是true
            if (System.getProperty("Logger.StandardOut", "false").equalsIgnoreCase("true")) {
                //控制台输出开关打开
                Logger.isToStandardOut = true;
            }
            //如果Logger.FrameWorkOut的值是false
            if (System.getProperty("Logger.FrameWorkOut", "true").equalsIgnoreCase("false")) {
                //框架默认日志开关关闭
                Logger.isDefault = false;
            }
            //如果Logger.Format的值为false
            if (System.getProperty("Logger.Format", "true").equalsIgnoreCase("false")) {
                //日志格式开关关闭
                Logger.isFormat = false;
            }
        }
     
     
    }
    
    1. DriverBase类
    package selenium.framework.demo.webdriver;
     
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.edge.EdgeDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import selenium.framework.demo.util.Base;
    import selenium.framework.demo.util.InitProperties;
    import selenium.framework.demo.util.Logger;
     
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
     
    /**
     * 驱动基础类
     */
    public class DriverBase extends Base{
     
        private static WebDriver dr=null;
        public static WebDriverPlus driver=null;
     
        //浏览器名称
        public static String browser=null;
     
        //设置的等待时间 是针对全局设置
        public static int implicitlyWait = 30; //隐式等待时间:秒,针对Driver 每次执行命令的 最长执行时间也可以理解为超时时间
        public static int webDriverWait = 30;//显示等待时间:秒,要等到某个元素的出现,等不到就一直等直到超时
     
        public static void launch(){
            //获取配置文件中的WebDriver.Browser的值
            browser = System.getProperty("WebDriver.Browser");
            //获取配置文件中的WebDriver.Browser.Location的值
            String browserLocation = System.getProperty("WebDriver.Browser.Location");
     
            /*Set<String> strings = InitProperties.mapproperties.keySet();
            for (String string : strings) {
                System.out.println("=================="+string+"==================");
            }*/
            if (browser.equalsIgnoreCase("Firefox")) {
                Logger.log("打开Firefox浏览器");
                if (browserLocation != null && !browserLocation.isEmpty()) {
                    //System.setProperty("webdriver.firefox.bin", browserLocation);
                    System.setProperty("webdriver.gecko.driver", browserLocation);
                }
                dr = new FirefoxDriver();
            } else if (browser.equalsIgnoreCase("Chrome")) {
                Logger.log("打开Chrome浏览器");
                if (browserLocation != null && !browserLocation.isEmpty()) {
                    System.setProperty("webdriver.chrome.driver", browserLocation);
                }
                dr = new ChromeDriver();
            }else if(browser.equalsIgnoreCase("Edge")){
                Logger.log("打开Edge浏览器");
                if (browserLocation != null && !browserLocation.isEmpty()) {
                    System.setProperty("webdriver.Edge.driver", browserLocation);
                }
                dr = new InternetExplorerDriver();
            } else{
                Logger.log("打开IE浏览器");
                if (browserLocation != null && !browserLocation.isEmpty()) {
                    System.setProperty("webdriver.ie.driver", browserLocation);
                }
                dr = new EdgeDriver();
            }
            driver = new WebDriverPlus(dr);
            //获取配置文件WebDriver.ImplicitlyWait的值并赋值给implicitlyWait
            implicitlyWait = Integer.parseInt(System.getProperty("WebDriver.ImplicitlyWait").trim());
            //获取配置文件WebDriver.WebDriverWait的值并赋值给webDriverWait
            webDriverWait = Integer.parseInt(System.getProperty("WebDriver.WebDriverWait").trim());
     
            Logger.log("设置全局显示等待:" + implicitlyWait);
            //设置超时时间
            driver.manage().timeouts().implicitlyWait(implicitlyWait, TimeUnit.SECONDS);
            //窗口最大化
            driver.manage().window().maximize();
        }
    }
     
    

    显式等待

    显式等待,就是明确的要等到某个元素的出现或者是某个元素的可点击等条件,等不到,就一直等,除非在规定的时间之内都没找到,那么就跳出Exception.抛出异常。这样就>通过回调函数,直接获得了这个WebElement.也就是页面元素.

    隐式等待

    隐式等待是针对Driver 每次执行命令的 最长执行时间也可以理解为超时时间。WebDriver会进行一个隐式等待,但参数只有时间,这就导致我需要什么元素出现,我不
    一定能等到它,得不到某个元素,就延迟一下...

    创建测试类

    1. clear工具类并install

    因为测试类要依赖工具类,所以必须要install才能是否

    1. 新建一个maven项目selenium.framework.demo

    pom文件

        <dependencies>
            <dependency>
                <groupId>selenium</groupId>
                <artifactId>selenium.framework</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
    
    1. 创建配置文件Config.properties文件
    ############################################################
    # WebDriver Configure
    ############################################################
    # (Firefox, Chrome or IE)
    WebDriver.Browser=Firefox
    WebDriver.Browser.Location=files\geckodriver.exe
    WebDriver.ImplicitlyWait=30
    WebDriver.WebDriverWait=30
     
    ############################################################
    # Log configure
    ############################################################
    #日志开关
    Logger = true
    #日志格式开关
    Logger.Format = true
    #框架默认日志开关
    Logger.FrameWorkOut = false
    #控制台输出开关
    Logger.StandardOut = true
    
    1. 浏览器驱动

    浏览器驱动

    1. 浏览器工具启动类
    package selenium.framework.test.util;
     
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.BeforeTest;
    import selenium.fromework.demo.webdriver.DriverBase;
     
    /**
     * 浏览器工具启动类
     */
    public class BrowerBase extends DriverBase{
        @BeforeTest
        public void beforeTestBase() {
            launch();
        }
     
        @AfterTest(alwaysRun=true)
        public void afterTest() {
            quit();
        }
     
        @BeforeClass
        public void beforeBaseClass() {
        }
     
        @AfterClass(alwaysRun=true)
        public void afterBaseClass() {
     
        }
     
        /**
         * quit browser
         */
        private void quit() {
            if (driver != null) {
                driver.quit();
                driver = null;
            }
        }
    }
    
    1. TestOpenBrowser类
    package selenium.framework.demo.test;
     
    import org.testng.annotations.Test;
    import selenium.framework.demo.util.BrowserBase;
    import selenium.framework.demo.util.Logger;
     
    public class TestOpenBrowser extends BrowserBase {
        @Test
        public void openBrowser(){
            Logger.log("打开" + browser + "浏览器");
     
            Logger.log("进入百度页面");
            String baseUrl = "https://www.baidu.com/";
            driver.get(baseUrl);
            delay(2);
            Logger.log("关闭" + browser + "浏览器");
        }
    }
    

    完整的项目结构

  • 相关阅读:
    3组Alpha冲刺5/6
    3组Beta冲刺4/5
    3组Alpha冲刺6/6
    3组Beta冲刺2/5
    3组Beta冲刺3/5
    delegate Demo (一个关于System.Timers.Timer的Demo)
    System.Web.HttpException 与 HTTP Error 404.13 Not Found问题解决说明
    常用SQL关于表的操作
    设计模式学习笔记:单例模式
    JS 实践杂记
  • 原文地址:https://www.cnblogs.com/liangfzh/p/13886171.html
Copyright © 2011-2022 走看看