From 3b9fd0aa6a020fd550ab45d134f183b6cc9723d4 Mon Sep 17 00:00:00 2001 From: ngosang Date: Sat, 24 Sep 2022 18:42:58 +0200 Subject: [PATCH] Add browser headless mode for Windows --- src/undetected_chromedriver/__init__.py | 7 ++++++- src/utils.py | 8 ++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/undetected_chromedriver/__init__.py b/src/undetected_chromedriver/__init__.py index 7926a9e..8e020fb 100644 --- a/src/undetected_chromedriver/__init__.py +++ b/src/undetected_chromedriver/__init__.py @@ -119,6 +119,7 @@ class Chrome(selenium.webdriver.chrome.webdriver.WebDriver): suppress_welcome=True, use_subprocess=False, debug=False, + windows_headless=False, **kw ): """ @@ -384,17 +385,21 @@ class Chrome(selenium.webdriver.chrome.webdriver.WebDriver): if not desired_capabilities: desired_capabilities = options.to_capabilities() - if not use_subprocess: + if not use_subprocess and not windows_headless: self.browser_pid = start_detached( options.binary_location, *options.arguments ) else: + startupinfo = subprocess.STARTUPINFO() + if os.name == 'nt' and windows_headless: + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW browser = subprocess.Popen( [options.binary_location, *options.arguments], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=IS_POSIX, + startupinfo=startupinfo ) self.browser_pid = browser.pid diff --git a/src/utils.py b/src/utils.py index e8f2c12..7b93ecf 100644 --- a/src/utils.py +++ b/src/utils.py @@ -43,8 +43,11 @@ def get_webdriver() -> WebDriver: # note: headless mode is detected (options.headless = True) # we launch the browser in head-full mode with the window hidden + windows_headless = False if get_config_headless(): - if os.name != 'nt': # not in windows + if os.name == 'nt': + windows_headless = True + else: start_xvfb_display() # if we are inside the Docker container, we avoid downloading the driver @@ -57,7 +60,8 @@ def get_webdriver() -> WebDriver: # downloads and patches the chromedriver # todo: if we don't set driver_executable_path it downloads, patches, and deletes the driver each time - driver = uc.Chrome(options=options, driver_executable_path=driver_exe_path, version_main=version_main) + driver = uc.Chrome(options=options, driver_executable_path=driver_exe_path, version_main=version_main, + windows_headless=windows_headless) # selenium vanilla # options = webdriver.ChromeOptions()