Protected by Copyscape
Powered By Blogger

Thursday, April 1, 2021

How to do the Automation Execution in Chrome Browser in Headless mode using Selenium WebDriver?

The major benefit of running the automated test in headless mode is that to increase the execution speed. The only below code you need to add in your code.

WebDriver driver;

ChromeOptions opt=new ChromeOptions();

opt.addArguments("--headless");

driver=new ChromeDriver(opt);

With the help of  below example you would see that the execution is happening without opening chrome browser. 

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.support.ui.Select;

import java.util.Iterator;

import java.util.Set;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Window
{

static WebDriver driver;


public static void main(String args[]) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","c:/Browser Executables/chromedriver.exe");

ChromeOptions opt=new ChromeOptions();
opt.addArguments("--headless");

driver=new ChromeDriver(opt);

driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.get("https://opensource-demo.orangehrmlive.com/");

WebElement lnk=driver.findElement(By.xpath("//*[text()='OrangeHRM, Inc']"));

lnk.click();

Set<String> noOfWondows=driver.getWindowHandles();
Iterator<String> i=noOfWondows.iterator();

String pWindow=i.next();
String cWindow=i.next();

System.out.println("parent id is :"+ pWindow);
System.out.println("child id is :"+ cWindow);


driver.switchTo().window(cWindow);

driver.findElement(By.xpath("//*[@class='btn-orange contact-ohrm ']")).click();

driver.switchTo().window(pWindow).close();

driver.switchTo().window(cWindow);
        WebElement noOfEmp=driver.findElement(By.xpath("//*[@id=\"Form_submitForm_NoOfEmployees\"]"));

Select select=new Select(noOfEmp);
List<WebElement> noOfoptions=select.getOptions();

for(int k=0;k<noOfoptions.size();k++)
{
select.selectByIndex(k);
Thread.sleep(1000);
System.out.println(noOfoptions.get(k).getText());
if(noOfoptions.get(k).getText().contains("9,000"))
{
break;
}
}
Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");


}
}

***********************************************************************************************************************************************************

I will be adding more concepts in my upcoming posts. Please keep me posted if you have any questions and concerns.



Best of Luck.

No comments: