I am looking for a solution to open the chrome browser with selenium in headless mode, do some actions and then switch within the same browser in normal
mode.
For example:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("headless")
browser = webdriver.Chrome('C:/chromedriver', options=chrome_options)
browser.get("https://www.google.de/")
# Do some actions in headless mode
browser.find_element_by_css_selector("#L2AGLb > div").click()
browser.find_element_by_css_selector("body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form > div:nth-child(1) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input").send_keys("Python rocks")
browser.find_element_by_css_selector("body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form > div:nth-child(1) > div.A8SBwf > div.FPdoLc.lJ9FBc > center > input.gNO89b").send_keys(Keys.ENTER)
# Open Browser
Is there a way to do this?
No, it won't be possible to open google-chrome in headless mode and moving forward shift to the headed mode.
When you configure an instance of a ChromeDriver using ChromeOptions()
, in the process of initiating a new Chrome Browsing Session the configuration gets baked into the chromedriver executable and will persist till the lifetime of the WebDriver and being uneditable. So you can't add any further ChromeOptions to the WebDriver instance which is currently in execution.
Even if you are able to extract the ChromeDriver and ChromeSession attributes e.g. Session ID, Cookies, UserAgent and other session attributes from the already initiated ChromeDriver and Chrome Browsing Session still you won't be able to change the set of attributes of the ChromeDriver.
A cleaner way would be to call driver.quit()
within tearDown(){}
method to close and destroy the current ChromeDriver and Chrome Browser instances gracefully and then span a new set of ChromeDriver and Chrome Browser instance with the new set of configurations.
You can find a couple of relevant discussions in: