Open In App

How to Open a Browser in Headless Mode in Selenium using Java?

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Selenium is an open-source web automation tool that supports many user actions to perform testing in the web browser.

Why Headless Browser?

Executing the automation code to run on a web browser is used to perform UI testing and functional testing, But sometimes while we run our automation scripts on the browser the page takes time to load all the UI and images which causes errors and is more time-consuming. Also, most of the CI systems are using the non-UI mode, so we need to automate scripts for Non-UI mode, that’s why the Headless browser comes into use.

Headless Browser

Headless browsers are acts like real web browsers but without any GUI, The automation script is executed like any other browser but it does not display any UI, they execute only in the background. In selenium, we have support for the Headless browser using “HtmlUnitDriver”, it executes the script in the non-GUI mode.

Running Selenium test cases using HTMLUnitDriver

To implement the selenium script in Headless Mode, add the dependency for “HtmlUnitDriver” from the maven repository.

 <dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>htmlunit-driver</artifactId>
   <version>4.5.0</version>
</dependency>

Import the dependency class

import org.openqa.selenium.htmlunit.HtmlUnitDriver;

Create an instance for HtmlUnitBrowser

HtmlUnitDriver driver=new HtmlUnitDriver();

Example

In this example, we run the selenium script in Headless Mode.

  1. Launch the geeksforgeeks website in non-GUI mode.
  2. Get the title of the page.

Java




import org.openqa.selenium.htmlunit.HtmlUnitDriver;
  
public class Geeks {
    @Test
    public void geekforgeeks()
    {
        HtmlUnitDriver driver = new HtmlUnitDriver();
        driver.get("https://www.geeksforgeek.org/");
  
        System.out.println("Title of the page is  "
                           + driver.getTitle());
  
        driver.close();
    }
}


Output:

This code will open the browser in headless mode and perform the testing.

Output

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads