Java chrome driver的封装

废话不多说,直接上代码

ChromeUtil

import org.openqa.selenium.Dimension;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 封装chrome driver
* @author songmin
*/

public class ChromeUtil {

private String downLoadPath = null;
private boolean isHeadless = false;
private boolean noPicture = false;
private boolean developmentMode = false;
private Integer height = 800;
private Integer width = 1300;

/**设置无头模式*/
public void setHeadless(boolean isHeadless){
this.isHeadless = isHeadless;
}

/**设置无图模式*/
public void setNoPicture(boolean noPicture){
this.noPicture = noPicture;
}

/**设置默认下载地址*/
public void setDownLoadPath(String path){
this.downLoadPath = path;
}

/**设置是否为开发者模式*/
public void setDevelopmentMode(boolean isDevelop){
this.developmentMode = isDevelop;
}

/**设置浏览器的大小*/
public void setHeightWithWidth(Integer height,Integer width){
this.height = height;
this.width = width;
}

/**获得一个chrome对象*/
public ChromeDriver getChorme(){
//调用chrome driver
System.setProperty("webdriver.chrome.driver", "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe");
DesiredCapabilities caps = initChromeOption();
//调用chrome
ChromeDriver driver = new ChromeDriver(caps);
//调整浏览器大小
driver.manage().window().setSize(new Dimension(width,height));
return driver;
}

/**初始化设置*/
public DesiredCapabilities initChromeOption() {
ChromeOptions options = new ChromeOptions();
DesiredCapabilities caps = new DesiredCapabilities();
if (isHeadless){
options.addArguments("-headless");
}
if (noPicture){
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.managed_default_content_settings.images", 2);
options.setExperimentalOption("prefs", prefs);
}
if (downLoadPath!=null){
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downLoadPath);
chromePrefs.put("profile.default_content_settings.popups",0);
options.setExperimentalOption("prefs", chromePrefs);
}
if (developmentMode){
List excludeSwitches = new ArrayList<String>();
excludeSwitches.add("enable-automation");
options.setExperimentalOption("excludeSwitches", excludeSwitches);
}
     
caps.setCapability(ChromeOptions.CAPABILITY, options);
        return caps;
}
}
 

使用示例


/**
* 封装chrome driver
* @author songmin
*/

public
class Test { public static void main(String[] args) throws InterruptedException { ChromeUtil chromeUtil = new ChromeUtil(); //设置为开发者模式 chromeUtil.setDevelopmentMode(true); //设置浏览器的高宽 chromeUtil.setHeightWithWidth(400,400); //设置为无头模式 chromeUtil.setHeadless(true); ChromeDriver driver = chromeUtil.getChorme(); driver.get("http://www.ushowtime.cn"); Thread.sleep(3000); driver.close(); } }

 

posted @ 2019-10-08 14:35  执笔coding  阅读(2328)  评论(0编辑  收藏  举报