Selenium and Headless Environment.


We can execute Selenium in a headless environment. The headless execution is a new trend followed in industry today since it is fast and supports more than one browser.

Firefox in headless mode, can be run once we configure the geckodriver path. We shall then use the FirefoxOptions class, and send the headless knowledge to the browser with setHeadless method and pass true as a parameter to it.

Syntax

FirefoxOptions o = new FirefoxOptions();
o.setHeadless(true);
WebDriver driver = new FirefoxDriver(o);

Example

Code Implementation.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class HeadlessFirefox{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      //FirefoxOptions object creation
      FirefoxOptions o = new FirefoxOptions();
      //set true to headless mode
      o.setHeadless(true);
      // add options parameter to Firefox driver
      WebDriver driver = new FirefoxDriver(o);
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/questions/index.php");
      // get page title
      System.out.println("Page Title in headless mode: " + driver.getTitle());
   }
}

Output

Updated on: 28-Dec-2020

784 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements