package jnpf.selenium.driver; import lombok.extern.slf4j.Slf4j; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.util.function.Supplier; @Slf4j public class ChromeBrowser extends AbstractBrowser { public static Supplier defaultDriverOptionsSupplier = () -> { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, getProperties().getDriverPath()); ChromeOptions options = new ChromeOptions(); //设置浏览器参数 options.addArguments("--headless"); options.addArguments("--disable-gpu"); options.addArguments("--no-sandbox"); options.addArguments("lang=zh_CN.UTF-8"); options.addArguments("--disable-dev-shm-usage"); //指定浏览器分辨率 options.addArguments("window-size=1920x1080"); //浏览器文件 if (StringUtils.hasText(getProperties().getBrowserPath())) { options.setBinary(getProperties().getBrowserPath()); } return options; }; public static Supplier defaultDriverServiceSupplier = () -> null; @Override public ChromeOptions buildDriverOptions() { return defaultDriverOptionsSupplier.get(); } @Override public ChromeDriverService buildDriverService() { return defaultDriverServiceSupplier.get(); } @Override public ChromeDriver buildDriver(ChromeDriverService driverService, ChromeOptions driverOptions) { Assert.notNull(System.getProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY), "未设置浏览器驱动路径"); ChromeDriver driver; if (driverService != null && driverOptions != null) { driver = new ChromeDriver(driverService, driverOptions); } else if (driverOptions != null) { driver = new ChromeDriver(driverOptions); } else if (driverService != null) { driver = new ChromeDriver(driverService); } else { throw new IllegalArgumentException("service 或 options 不允许都为空"); } return driver; } }