How to ConfigureChromeDriver for Headless Chrome in Selenium
In web scraping scenarios, executing Chrome browser in headless mode is often desired to avoid the display of browser windows. While the 'headless' option in ChromeDriver effectively prevents the display of the browser window, it may leave the executable file (.exe) running visibly.
Problem:
When using ChromeDriver with the 'headless' option, the .exe file remains visible, despite the browser window being hidden.
Code:
from selenium import webdriver options = webdriver.ChromeOptions() options.add_experimental_option('excludeSwitches', ['ignore-certificate-errors']) options.add_argument('headless') options.add_argument('window-size=0x0') chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"
This code initializes ChromeDriver with the 'headless' and 'window-size=0x0' options, but the .exe file still appears.
Solutions:
1. Update to Selenium 4.x (2023-05-22 Update)
Chrome's Headless mode has been overhauled. For headless/headful unification, append the '--headless=new' argument:
from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless=new') driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)
2. Original Answer (2018-10-26 Update)
Utilize the headless=True parameter of ChromeOptions() to initiate ChromeDriver in headless mode:
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)
Note that '--disable-gpu' may also be necessary for proper operation.
The above is the detailed content of How to Prevent ChromeDriver .exe from Running Visibly in Headless Chrome?. For more information, please follow other related articles on the PHP Chinese website!