How can I display a headless browser with Python?

I’ve set up a headless Chrome browser using the following argument:

chrome_options.add_argument('--headless')

I then initiate the browser like this:

driver = webdriver.Chrome(executable_path='/path/to/chromedriver', options=chrome_options)

Is there a way to show the browser window once a certain condition is satisfied? I attempted to remove the attribute with:

chrome_options.arguments.remove('--headless')

but it appears to change nothing. Any ideas?

you can’t change from headless to GUI mid-session. better start a new driver instance when your condition is met. setting headless mode is only at init.

Based on my experience experimenting with headless browsers, trying to change the mode after initializing the driver isn’t straightforward and often doesn’t work as expected. It’s typically better to open two separate browser instances based on the conditions you have. For instance, you can initiate one instance in headless mode and another in normal mode. Then, whenever your condition is met, you close the headless driver and switch to the normal one. Something like this should be more stable:

from selenium import webdriver

# Start headless Chrome
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
headless_driver = webdriver.Chrome(executable_path='/path/to/chromedriver', options=chrome_options)

# Your check condition
if some_condition_met:
    # Close headless driver
    headless_driver.quit()
    
    # Start normal Chrome
    chrome_options = webdriver.ChromeOptions()
    normal_driver = webdriver.Chrome(executable_path='/path/to/chromedriver', options=chrome_options)
    
    # Continue actions with normal_driver

Setting this up correctly from the start of your script often results in smoother transitions and fewer issues with managing the state of your WebDriver sessions.

Switching between headless and normal mode in a single instance of Selenium WebDriver is tricky and not supported directly. A more reliable way I found is to use separate instances for headless and non-headless modes, initiating them based on your conditions. Starting your headless mode initially and launching the GUI instance when required might be a smoother approach. This ensures the session management remains intact and your transitions are seamless.