大佬教程收集整理的这篇文章主要介绍了如何使用 Java + Selenium 确定 Chrome 是否在 Headless 模式下运行,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个像这样初始化的网络驱动程序:
public DriverInit() throws MalformedURLException {
try {
System.out.println(Main.absoluteDownloadfilePath);
// Create a map to store preferences (to disable pop-up notifications)
Map<String,Object> prefs = new HashMap<String,Object>();
// add key and value to map as follow to switch off browser notification
// Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setTing_values.automatic_downloads",1);
prefs.put("profile.default_content_setTings.popups",0);
prefs.put("download.default_directory",Main.absoluteDownloadfilePath);
// for local automated tesTing
this.ChromeOptions = new ChromeOptions();
ChromeOptions.setExperimentalOption("prefs",prefs);
ChromeOptions.addArguments("start-maximized");
ChromeOptions.addArguments("--disable-extensions");
ChromeOptions.addArguments("--headless");
String ChromeDriverPath = "resources" + file.separator + "chromedriver.exe";
System.setProperty("webdriver.Chrome.driver",ChromeDriverPath);
this.driver = new ChromeDriver(ChromeOptions);
System.out.println("new Chrome driver started.....");
this.driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
} catch (Exception E) {
System.out.println("Could not not initialize driver: " + e.getmessage());
}
}
有没有什么办法可以写一个函数来判断驱动是否无头?我需要写一个 if-else 语句:
if (driver is headless){
// some code
}else{
// some code
}
我试过这个函数,但它没有返回我需要的:
public ChromeOptions getChromeOptions() {
return this.ChromeOptions;
}
它只打印 CapabilitIEs {Browsername: ChromE}
,所以没有提到它是否无头。
ChromeOptions option = new ChromeOptions();
option.addArguments("--headless");
System.setProperty("webdriver.chrome.driver","chromedriverpath");
WebDriver driver = new ChromeDriver(option);
driver.get("https://google.com");
使用 JavascriptExecutor 返回 window.navigator.userAgent 的值
String browser = (String) ((JavascriptExecutor) driver).executeScript(" return window.navigator.userAgent");
if (browser.contains("HeadlessChrome")) {
System.out.println("Chrome is headless");
} else {
System.out.println("Chrome is not headless");
}
System.out.println(browser);
O/P:
Chrome 是无头的
Mozilla/5.0(Windows;Intel 10)AppleWebKit/537.36(KHTML,如 Gecko)HeadlessChrome/91.0.4472.114 Safari/537.36
以上是大佬教程为你收集整理的如何使用 Java + Selenium 确定 Chrome 是否在 Headless 模式下运行全部内容,希望文章能够帮你解决如何使用 Java + Selenium 确定 Chrome 是否在 Headless 模式下运行所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。