zoukankan      html  css  js  c++  java
  • java+selenium+testng(二)打开/关闭浏览器

    1、操作浏览器,需要先下载浏览器驱动

    chrome浏览器驱动下载地址:http://npm.taobao.org/mirrors/chromedriver/

    firefox浏览器驱动下载地址:https://github.com/mozilla/geckodriver/releases

    下载完成后可以放到  src/test/resources  目录下

    
    

    2、导入依赖

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
    

      

    3、打开浏览器的代码(BrowserUtil)

    /**
    * 打开浏览器
     * @param browserType  打开浏览器的类型
    */
    public static void openBrowser(String browserType){
        browserName = browserType;
        if(browserType != ""){
            if(browserType.equals("chrome")){
                System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");            
                WebDriver driver = new ChromeDriver();
                setDriver(driver);
                logger.info("========打开chrome浏览器========");
            }else if(browserType.equals("firefox")){
                //代码省略
           logger.info("========打开firefox浏览器========");
         }else if(browserType.equals("ie")){ 
          
    //代码省略
          
    logger.info("========打开ie浏览器========");
        }
      }
    }

     

    4、关闭浏览器代码(BrowserUtil)

    /**
     * 关闭浏览器
    */
    public static void closeBrowser() {
        logger.info("========关闭浏览器========");
        getDriver().quit();
    }

     

     

     

     

    PS,经济实用的无头浏览器模式写法

    (在没有桌面GUI的情况下,可以使用无头浏览器模式。我个人在调试代码的时候,不喜欢在本地打开太多页面,也直接使用了本地浏览器),下面介绍下无头浏览器模式的写法,以chrome浏览器为例

    System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
    //支持chrome无头浏览器模式
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("headless");
    WebDriver driver = new ChromeDriver(chromeOptions);
    setDriver(driver);
    logger.info("========打开chrome浏览器========");

     

  • 相关阅读:
    【转载】Linux下各文件夹的含义和用途
    【转载】Linux 通过mount -o loop 配置本地.iso镜像为yum源(yum仓库)
    Fedora 和 RedHat 以及 SUSE 中 YUM 工具的使用
    【转】下载对应内核版本的asmlib
    【转】VMWare vCenter 6.0安装配置
    【转】在VMware中为Linux系统安装VM-Tools的详解教程
    【转】虚拟化(五):vsphere高可用群集与容错
    html拼接时onclick事件传递json对象
    bootstrap table 解析写死的json.并且把进度条放进列中。
    开发规范实体和值对象
  • 原文地址:https://www.cnblogs.com/x495122903/p/13362206.html
Copyright © 2011-2022 走看看