Friday 14 September 2018

How to run Chrome & Firefox Webdriver in Headless mode

Headless Browser! What does it mean.? As name suggests, It is a browser without head.i.e., without GUI. 

Headless Browsers are a kind of simulation programs of real browsers, but without GUI. Having said that, these may not be 100% equal to real browsers as they have its own limitations. Here are few popular headless browsers:

  • Headless Chrome
  • Headless Firefox
  • HtmlUnit Driver
  • PhantomJS
  • SlimmerJS

Headless browsers come with its own Pros & Cons.
Pros:

  • Improves the execution speed,in turn increases the performance.
  • Can be executed on Browser-less setups like Servers(without browsers).
  • Useful while scraping the web.
  • Simulate multiple browser versions on a single machine.

Cons:

  • It doesn't mimic the real user.
  • Debugging is quite difficult.

Below snippet would show you, How to make Chrome & Firefox work in Headless mode.


static String chromeDriverPath = "C:/pathTo/chromedriver.exe";
static String geckoDriverPath = "C:/pathTo/geckodriver.exe";
static WebDriver driver = null;

public static void main(String[] args) throws Exception{
System.setProperty("webdriver.chrome.driver",chromeDriverPath);
System.setProperty("webdriver.gecko.driver",geckoDriverPath);

//For Headless Chrome
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
    //OR
//options.setHeadless(true);
driver = new ChromeDriver(options);
        
//For Headless Firefox
FirefoxOptions foption = new FirefoxOptions();
foption.setHeadless(true);
driver = new FirefoxDriver(foption);
        
driver.get("https://www.amazon.in/");
driver.manage().window().maximize();
System.out.println("Browser Title: " + driver.getTitle());
driver.findElement(By.xpath("//div[@class='a-section feed-carousel first-carousel']//ul/li[1]")).click();
Thread.sleep(5000);
    
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:/screens/Headless.jpg"));

driver.close();

}



2 comments:

  1. Thanks for providing the information . The articles in your blog helped me a lot for improving the knowledge on the subject. Also check my small collection on this at selenium Online Training blog

    ReplyDelete
  2. I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details. Impressive blog with lovely information. Really very useful article for us.

    Selenium Automation testing

    ReplyDelete