簡體   English   中英

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

[英]How to determine if Chrome is running in Headless mode with Java + Selenium

我有一個像這樣初始化的 Web 驅動程序:

    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, like Gecko) HeadlessChrome/91.0.4472.114 Safari/537.36

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM