微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Java + Selenium 确定 Chrome 是否在 Headless 模式下运行

如何解决如何使用 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);

参考:check here

O/P: Chrome 是无头的
Mozilla/5.0(Windows;Intel 10)AppleWebKit/537.36(KHTML,如 Gecko)HeadlessChrome/91.0.4472.114 Safari/537.36

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。