Headless browser execution lets you run tests without opening a visible browser window. This makes tests faster and can run on servers without screens.
0
0
Headless browser execution in Selenium Python
Introduction
When you want to run automated tests on a server without a graphical interface.
When you need faster test runs by skipping browser display.
When running tests in continuous integration pipelines.
When you want to save computer resources during testing.
When debugging is not needed with a visible browser.
Syntax
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(options=options) driver.get('https://example.com') # Your test steps here driver.quit()
Set options.headless = True to enable headless mode.
Remember to quit the driver to close the browser session.
Examples
This example opens a headless Chrome browser, navigates to example.com, prints the page title, then closes the browser.
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(options=options) driver.get('https://example.com') print(driver.title) driver.quit()
This example uses Firefox in headless mode to open a page and print the current URL.
Selenium Python
from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.headless = True driver = webdriver.Firefox(options=options) driver.get('https://example.com') print(driver.current_url) driver.quit()
Sample Program
This test script runs Chrome in headless mode, opens example.com, prints the page title, and closes the browser.
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(options=options) driver.get('https://example.com') page_title = driver.title print(f'Page title is: {page_title}') driver.quit()
OutputSuccess
Important Notes
Headless mode may behave slightly differently than normal mode; test carefully.
Use headless mode for faster and resource-friendly test runs.
To debug, run tests without headless mode to see the browser.
Summary
Headless browser execution runs tests without showing the browser window.
It is useful for running tests on servers and speeding up test runs.
Set the browser options to headless before creating the driver.