How to Run Selenium Tests in Headless Mode

 Selenium is a popular framework for automating web application testing. While running tests with a visible browser can be helpful during development, headless mode is often preferred in CI/CD pipelines or automated environments where GUI interaction is not needed. Headless mode allows tests to run without opening a browser window, making them faster and more resource-efficient.

Here’s a step-by-step guide on how to run Selenium tests in headless mode using Python and Chrome.

What is Headless Mode?

Headless mode runs a browser without its user interface. It behaves just like a regular browser but doesn’t display any visual window. This is ideal for automation scripts, especially when running tests on servers or virtual machines.

Installing Selenium and WebDriver

First, make sure you have Selenium and the appropriate WebDriver installed:

pip install selenium

Download the ChromeDriver compatible with your Chrome version from the official site.

Running Selenium in Headless Mode (Python Example)

from selenium import webdriver

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.chrome.options import Options

# Setup Chrome options

options = Options()

options.add_argument("--headless")  # Enable headless mode

options.add_argument("--disable-gpu")  # Optional: useful for Windows OS

options.add_argument("--window-size=1920,1080")  # Set window size

# Path to your ChromeDriver

service = Service("path/to/chromedriver")

# Launch the browser

driver = webdriver.Chrome(service=service, options=options)

# Open a website

driver.get("https://example.com")

print(driver.title)

# Close the browser

driver.quit()

Why Use Headless Mode?

Speed: Tests run faster since there's no rendering overhead.

Resource Saving: Uses less CPU and memory.

CI/CD Compatibility: Ideal for automated pipelines that lack GUI environments.

Debugging Tips

Since you can’t visually see what’s happening:

Use screenshots: driver.save_screenshot("screenshot.png")

Log page titles and source

Enable verbose logging for better traceability

Conclusion

Running Selenium tests in headless mode is a smart choice for automation, especially in production and continuous integration environments. It enhances performance, reduces costs, and allows seamless execution of test suites without graphical dependencies. By tweaking just a few lines of code, you can ensure your tests run silently and efficiently behind the scenes.

Learn Selenium Java Training in Hyderabad

Read More:

Automating Web Forms Using Selenium Java

Using TestNG with Selenium for Test Automation

Understanding Page Object Model in Selenium Java

Taking Screenshots with Selenium in Java

Visit our IHub Talent Training Institute

Get Direction









Comments

Popular posts from this blog

SoapUI for API Testing: A Beginner’s Guide

Automated Regression Testing with Selenium

Containerizing Java Apps with Docker and Kubernetes