I'm writing a selenium test which has different behavior given whether the chrome browser was started as headless or not. My question is in my test how do I detect if the browser is headless for my conditional flow?
driver.execute_script("return navigator.plugins.length == 0")
driver.execute_script("return navigator.webdriver") is True
is the way –
Loyola Considering this scenario:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920,1080")
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
In my testing I found that driver.get_window_position()
returns {'x': 0, 'y': 0}
when running in headless mode.
However when run without the headless option it defaults to {'x': 10, 'y': 10}
.
I'm using this method to determine if my Chrome instance is running in headless mode by simply doing:
assert driver.get_window_position()['x'] == 0
assert driver.get_window_position()['y'] == 0
I just find this way for that.
Options its a list, so you have to find the "--headless" element in there.
opc = Options()
opc.add_argument('headless')
in this case, the position of the element in the list is [0], so you only have to to something like this:
if (opc.arguments[0]=="--headless"):
print("Do something")
I know the question is about Chrome, but if you're using Firefox, there is a cleaner solution (tested on Firefox 106):
if driver.caps.get("moz:headless", False):
print("Firefox is headless")
You need to explicitly add the argument "--headless" to your chromeOptions object when starting an instance of chrome headlessly. If you're writing, for example, a test framework for a website you probably have some sort of browser creator class that is able to give you different browsers to work with. Why not save that argument as an additional member of that class?
Another simpler option if you don't have a that sort of factory design in your code is just
options = webdriver.ChromeOptions
options.add_argument("--headless")
print(options.arguments)
© 2022 - 2024 — McMap. All rights reserved.