Protected by Copyscape
Powered By Blogger

Wednesday, April 21, 2021

What are the ways of capturing a snapshots in functional Automation using Selenium API?

Generally, People use an interface called TakeScreenshot to capture a snapshot with Selenium WebDriver. But the only limitation I see here that it captures only the visible area of the screen but what happened if  the requirement is to capture the snapshot from top to bottom in one go like in Amazon.com where multiple products are listed and we need to capture the snapshot from top to bottom.

In this scenario TakeScreenshot will fail as this will capture only the visible area not top to bottom in one go. Here, in this scenarion we can take help from AShot which is a third party API which can be integrated with Selenium API to capture the screenshot from top to botton.


First, we will see that how we capture a snapshot using TakeScreenshot interface. The below code will help to capture the visible area of the screen.

import io.github.bonigarcia.wdm.WebDriverManager;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenShot
{
static WebDriver driver;

public static void main(String args[])
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("https://www.google.co.in");

File Src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(Src, new File("c:/vikas/img.jpg"));
}
catch(IOException io)
{
System.out.println(io.getMessage());
}
}

}  


or the above same thing we can do with the help of AShot. Please see the below code where I have shown that how we can capture the snapshot using AShot.

First, download the dependency for AShot from MVN Repository and add it to your Maven or Gradle project.

import io.github.bonigarcia.wdm.WebDriverManager;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenShot
{
static WebDriver driver;

public static void main(String args[])
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("https://www.google.co.in");

Screenshot screenshot=new AShot().takeScreenshot(driver);
try {
ImageIO.write(screenshot.getImage(), "PNG", new File("C:/Vikas/img.png"));
}
catch(IOException io){
System.out.println(io.getMessage());
}
}
}

Now, how we can utilize AShot in case the full screenshot needs to be captured from top to bottom. Please see the below code.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenShot
{
static WebDriver driver;

public static void main(String args[])
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("https://www.google.co.in");
driver.findElement(By.name("q")).sendKeys("StapleAutomationSolutions");
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);

Screenshot screenshot=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(10)).takeScreenshot(driver);
try {
ImageIO.write(screenshot.getImage(), "PNG", new File("C:/Vikas/img.png"));
}
catch(IOException io)
{
System.out.println(io.getMessage());
}
}
}

Now, If there is need to capture the snapshot for a specific element or an object. Please use the below code.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.coordinates.WebDriverCoordsProvider;


import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenShot
{
static WebDriver driver;

public static void main(String args[])
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("https://www.yahoo.com");

WebElement Yahoologo=driver.findElement(By.id("header-logo"));
Screenshot screenshot=new AShot().coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver,Yahoologo);
try {
ImageIO.write(screenshot.getImage(), "PNG", new File("C:/Vikas/img.png"));
}
catch(IOException io)
{
System.out.println(io.getMessage());
}
}
}

OR

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenShot {
static WebDriver driver;

public static void main(String args[]) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("https://www.yahoo.com");

WebElement Yahoologo = driver.findElement(By.id("header-logo"));

File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

Point location = Yahoologo.getLocation();
int width = Yahoologo.getSize().getWidth();
int height = Yahoologo.getSize().getHeight();
try {
BufferedImage fullimage = ImageIO.read(src);
BufferedImage subImage = fullimage.getSubimage(location.getX(), location.getY(), width, height);
ImageIO.write(subImage, "PNG", src);
FileUtils.copyFile(src, new File("C:/Vikas/img.png"));

} catch (IOException io) {
System.out.println(io.getMessage());
}
}
}

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



Best of Luck.



How to run your Selenium test in headless mode with the available browsers? What are their advantages & disadvantages for the same?

Running test in headless mode, using Selenium API, will increase the execution speed as all the execution will be carried out without the involvement of any UI.

Until recently, modern browsers like Chrome and Firefox did not offer any built-in support for running their browsers in Headless mode. QA engineers would use open-source headless browsers such as PhantomJS or Zombie JS to achieve this purpose. However, much-awaited headless mode is made available, for Chrome 59 and Firefox 56 versions and higher.

Now, we will see that what changes needs to be done in the code to run the script in headless mode for each browser.

  • Chrome
  • Firefox
Chrome

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

WebDriver driver=new ChromeDriver(options);

Firefox 

FirefoxOptions firefoxOptions=new FirefoxOptions();
firefoxOptions.setHeadless(true);
driver=new FirefoxDriver(firefoxOptions);

Advantages of Headless Browser Testing

Since Headless browsers, do not have a GUI, they save a lot of resources and time. Following are some of the biggest advantages of headless browser testing:

  • Improves speed and performance – Since this type of testing does not actually open a browser, the system saves the processing power that would be used in a real browser test. Due to this, the tests are executed faster.
  • Allows testing browser-less setups – There may be setups where installing a browser is not possible, such as servers. In these cases, headless browsers help run automation tests easily.
  • Makes multi-tasking possible – One can use the browser or machine to continue doing other work, while the tests run in the background. This saves a lot of hours that is, otherwise, spent staring at the screen.
  • Minimum Human Intervention – There are fewer chances of failure and reduced errors due to minimum ‘human intervention.’
  • Taking Screenshots is Possible – Any desired screenshots are still stored, just like in regular automation testing.

Disadvantages of Headless Browser Testing

Running tests on headless browsers do have a few disadvantages. Some of them are as follows:
  • Lacks Actual User Experience- Running headless tests cannot give real feel and experience. One cannot really mimic the real user experience.
  • UI issues can’t be identified– Cosmetic bugs can’t be identified while doing headless browser testing. Issues like the location of a button or colour of a web element, etc. cannot be identified.
  • Hard to debug inconsistent failures– When it comes to debugging, headless browsers may not be the best option to find out Inconsistent errors and failures.
Limitations
  • Rendering: User could not feel how UI is rendering.
  • Resizing & page height: User cannot resize the page in headless testing.
  • User cannot use IE10, IE11, Edge, Opera & Safari for headless testing.

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



Best of Luck.

Friday, April 16, 2021

What is Self-healing process in Automation testing? Why it's required?

Self-healing is the technique or tool which makes the Automation scripts enough capable so that script can fix the issues itself if any failure occurs, due to Object or Web element description changes, during run time. 

It applies Artificial Intelligence & Machine Learning algorithm internally to updates the Object Repository if any discrepancy found in already stored Object's description in the repository so that Script should run smoothly without any failure.

Below is the diagram which shows the difference between present & traditional way of identifying an Object. 


 
When a script fails, manual object identification maintenance can take up to 15 minutes per occurrence. A script fails when object properties change, and an automation engineer must stop developing new scripts to troubleshoot and fix the broken one. The team manually inspects or spies the object to see the new property value or find new properties to use, then updates the script or object repository accordingly and reruns the script.

Suppose if there is one application deployment per week and we encounter around 35 object changes (which varies greatly based on application maturity, development methodology, size of project, etc.). At 15 minutes per manual fix, the result is more than one person’s full workday i.e. 8.75 hours & spent per week on basic automation maintenance.

Self-healing automation is a solution of test automation script maintenance: object changes. The “object,” such as a button or text box on a web page that the script (or the user) would interact with to perform the actions. Scripts must be able to uniquely identify an object on which it needs to perform an action like Enter a user name in a text box.

Just as a person can be identified by physical attributes such as size, hair color or eye color or by other relative means (“that person we saw at the store yesterday”) objects must also be uniquely identified in some way. And, just as people’s appearances can change to the point that they aren’t recognizable to others, objects that no longer fit their original “description” can confuse traditional automation scripts. When that happens, scripts break and downtime accumulates.

Self-healing employs data analytics to identify objects in a script even after they have changed. Self-healing approach introduces a higher level of intelligence and analysis.

When your script fails due to being unable to find the object it expected, the self-healing mechanism provides a fuller understanding and analysis of options. Rather than shutting down the process, it examines objects holistically, evaluates attributes and properties of all available objects and uses a weighted scoring system to select the one most similar to the one previously used. Self-healing can scrape, evaluate and choose among 10 objects in less than 0.05 seconds. Stop and-go syndrome is effectively cured.

The self-healing difference can be fully realized as it:

• Changes the mindset regarding automation approaches
• Allows automation efforts to start earlier as fears of maintenance subside
• Automates the maintenance process itself in real time
• Improves or preserves the return on investment



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



Best of Luck.

Wednesday, April 7, 2021

What is Sikuli? How Sikuli can be integrated with Selenium WebDriver?

Sikuli is an Open Source GUI based Automation tool. This tool helps us to recognize the web objects if webdriver is unable to locate the web element based on the XPATH or CSS locators. 

Sikuli uses the technique of "Image Recognition" & "Control GUI" to interact with Web Elements. All the Web Elements are taken as images and stored inside the project.

To integrate Sikuli with Selenium Web Driver first we need to download the latest JAR from the following url.

https://raiman.github.io/SikuliX1/downloads.html

The above jar file will help us to integrate the Web Driver with Sikuli. So, please add this jar dependency in your IDE either Eclipse or Intellj. In the below screen you can see that I have added or integrated the Sikuli jar with the project.


In Sikuli we have 3 major classes which it supports 'Region', 'Match' & 'Screen'. In this tutorial we will focus on Screen class and its methods. Below are the methods which Screen class supports.


Here, I am automating the login screen of facebook and assume that login button is not identifying by WebDriver using locators like Xpath or CSS. So, I will use here Sikuli to perform click event on the login button.

Please save the image of login button in c: drive in .PNG format. After that give that image reference to Pattern Class like below.


Screen s=new Screen();
Pattern loginButton=new Pattern("c:/fblogin.png");
s.click(loginButton);

Below is the code which I have written in Intellj IDE to perform click even on login button of facebook page.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.testng.annotations.Test;
import org.sikuli.script.Screen;


import java.util.concurrent.TimeUnit;

public class FBLogin
{
@Test
public void login() throws FindFailed
{

System.setProperty("webdriver.chrome.driver","c:/Browser Executables/chromedriver.exe");
Screen s=new Screen();
Pattern loginButton=new Pattern("c:/Images/fblogin.PNG");

WebDriver driver;
driver=new ChromeDriver();

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

driver.get("https://www.facebook.com");

driver.findElement(By.xpath("//*[@id='email']")).sendKeys("Vikas4903");
driver.findElement(By.xpath("//*[@id='pass']")).sendKeys("Vikas4903");
s.click(loginButton);

driver.close();
}
}

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



Best of Luck.

Tuesday, April 6, 2021

How Selenium Web Driver API works internally?

Here in this post, I am going to explain the Selenium Web Driver Architecture which is a very basis question during interviews now a days.

Selenium WebDriver is an API which supports many languages like Java, C#, Python etc. 

API (Application Programming Interface) works as an interface between various software components. Selenium WebDriver API helps in communication between languages and browsers.

Below is the framework architecture diagram of  Selenium Web Driver.


Major four components we have in the above diagram.

  • Selenium Client Library
  • JSON Wire Protocol
  • Browser Executable Drivers
  • Browsers
Selenium client library consist of multiple languages like Java, C#, Python, Ruby etc. Once the test cases are triggered the code written in Java or in any other supported language it gets converted into  JSON format.

JSON stands for Java Script Object Notation which is responsible for transferring the JSON code to the Browser Driver using HTTP Protocol. JSON Wire Protocol is responsible for transfer of data between HTTP servers

Each Browser has a dedicated browser driver. Browser driver interacts with its respective browser and execute the commands by interpreting JSON which they receive from the Browser. When Browser driver gets any instruction they run them on the Browser and response is given back in the form of HTTP Response.


Take an example of the below code

WebDriver driver=new ChromeDriver();

driver.get("http://www.google.co.in");

When we run the above block of code, the entire code will be converted with the help of JSON Wire Protocol over HTTP as a URL. The converted URL will be given to the ChromeDriver.

The browser driver utilizes HTTP server to get the request from HTTP. As the browser driver gets the URL, it passes the request to its browser via HTTP. It will trigger the event of executing the Selenium instructions on the browser.


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



Best of Luck.

Sunday, April 4, 2021

What is Page object Model ? How we can implement this using Selenium API?

Page Object Model or POM is nothing but a design pattern which you can use to make your Automation framework more readable and reusable. The major benefit of this would be the maintenance of your framework would be less.

In POM we store all locators and methods in separate Java class and we can use these classes while writing the test scripts. It means first you will create the java class for each page and then store the description of each web element of that page inside that class along with the relevant actions in terms of method which you want to perform on the web elements. The benefit of using POM would be if any change or update happen in the web element locator then you have to make change in a respective page where you have defined the locator for it and that change would be reflected everywhere wherever you are using the web element in the entire framework.

POM can be implemented by using the below 2 ways:

  1. POM without Page Factory
  2. POM with Page Factory

The only difference I see between with Page Factory and without Page factory is that with Page Factory we get the Cache lookup feature which allow us to store the frequently used locators in the cache which makes the retrieval performance faster.

Now I will explain that, how we can implement POM without Page Factory? 

First, we need to see that how many pages we have in the Web Application which we are going to automate. Suppose, we are going to Automate facebook.com.

In Facebook, we have the following basic pages.

  • Login Page
  • Forgotten Password
  • Create New Account etc.

In the below example I have created three packages with the following names

  • com.facebook.base
  • com.facebook.pages
  • com.facebook.testcases

👉Inside com.facebook.base package I have created one java class with the name of "StartUp.java" which is the starting point of the execution as it contains 2 annotations @Beforesuite & @Aftersuite. Below is the code which I have written inside the StartUp class.

package com.facebook.base;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import java.util.concurrent.TimeUnit;

public class StartUp
{
public static WebDriver driver;

@BeforeSuite
public static void setUp()
{
System.setProperty("webdriver.chrome.driver","c:/Browser Executables/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://www.facebook.com");

}
@AfterSuite
public static void tearDown()
{
driver.close();
}
}

👉Inside com.facebook.page package I have created a class called LoginPage where I have defined all the locators which belongs to the facebook login page. Now, you have to create another pages for "Forgotten Password" and "Create New Account" where all locators should be defined in similar format like Login Page.

 package com.facebook.pages;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage
{
public WebDriver driver;

//Define all the locators below which are on login page.
By id=By.id("email");
By pwd=By.xpath("//*[@id='pass']");
By btnlogin=By.xpath("//*[@name='login']");

public LoginPage(WebDriver driver)
{
this.driver=driver;
}
public void typeUserName(String UName)
{
driver.findElement(id).sendKeys(UName);
}
public void typePassword(String pass)
{
driver.findElement(pwd).sendKeys(pass);
}
public void clickOnLogin()
{
driver.findElement(btnlogin).click();
}

}

👉Inside com.facebook.testcase package I have created one test case with the name of ValidateFBLogin. Further test cases would be created inside this package for Forgotten Password and Create New Account Scenario. Below is the code for the same.

package com.facebook.testcases;

import com.facebook.base.StartUp;
import com.facebook.pages.LoginPage;
import org.testng.annotations.Test;

public class ValidateFBLogin extends StartUp
{
@Test
public void validatelogin()
{
LoginPage l=new LoginPage(driver);
l.typeUserName("vikas4903");
l.typePassword("ffffffff");
l.clickOnLogin();
}
}

So, this is the way to implement the POM without PageFactory. Now we should see the implementation of POM with Page Factory mode. I have created another page class i.e. "ForgotPwdPage" inside com.facebook.page package.
The following way we use to define the locators in POM with Page Factory.

@FindBy(how=How.XPATH,using="//*[text()='Forgotten password?']")
@CacheLookup
WebElement lnkForgotLink;

@FindBy(id="identify_email")
@CacheLookup
WebElement txtmobile;
Please find the below complete code.
package com.facebook.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class ForgotPwdPage
{

@FindBy(how=How.XPATH,using="//*[text()='Forgotten password?']")
@CacheLookup
WebElement lnkForgotLink;

@FindBy(id="identify_email")
@CacheLookup
WebElement txtmobile;

public void enterData(String mobNumber)
{
lnkForgotLink.click();
txtmobile.sendKeys(mobNumber);
}
}
Now we need to see that how we can call or use the methods inside the com.facebook.testcase package. Please find the below code.

package com.facebook.testcases;

import com.facebook.base.StartUp;
import com.facebook.pages.ForgotPwdPage;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;

public class ValidateForgotFunction extends StartUp
{
@Test
public void ChkFunctionality()
{
ForgotPwdPage f= PageFactory.initElements(driver,ForgotPwdPage.class);
f.enterData("7011516489");
}
}

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



Best of Luck.

Thursday, April 1, 2021

Is it possible to do the execution in already opened Browser using Selenium API? Why it's required?

Yes, it's possible to do the execution in the already opened browser but your browser should support Remote Debugging. In case of Chrome it's supports remote debugging feature if you have Chrome version 63 or above is available in the System. 

Why it's required?

When we design scripts for Automation Scenarios then there is always a need of debugging the code to fix the issues if any issues found by the script during the run like Object description needs to be updated , Sync issues etc. After fixing such issues we have to re-run the entire script to validate the fix which is a time consuming process.

But if we manually navigate to the page where the fix is required and then verify the fix by running few lines of code using Selenium API on the existing opened browser. So, by doing this way we will get rid of re-run the automation script again and again to validate the fix. To do the same following steps needs to be done.

1. Remote Debugging feature must be configured for Chrome browser by using the following steps:

    a. Try to access your Chrome browser through Command Prompt by typing Chrome.exe command in CMD. If you are unable to access Chrome browser using CMD then you have to set the path or reference for Chrome.exe in System Environment Variables. In my system, chrome.exe is located at 

"C:\Program Files\Google\Chrome\Application". 

So, the same you need to locate in your system and set the path or reference in System Environment Variables. Now try to access the same by typing "Chrome.exe" in CMD.



     b. Now run the following command in the command prompt to configure the Chrome for Remote Debugging purpose.

            Chrome.exe -remote-debugging-port=2323 --user-data-dir="C:/Selenium/Chrome_Test_Profile"



2. Now we have to use ChromeOptions class to do the necessary setup for the same.

System.setProperty("webdriver.chrome.driver","c:/Browser Executables/chromedriver.exe");
ChromeOptions opt=new ChromeOptions();

opt.setExperimentalOption("debuggerAddress","localhost:2323");
WebDriver driver;
driver=new ChromeDriver(opt);

Only the above 2 steps are required to perform to do the execution on the existing browser.

The following example you can try to practice the same.

1. Open facebook.com in the browser which you just opened by using the command which is mentioned in the above point 1 (b).

2. Click on Forgot Password link and then execute the following code to do the execution in the same browser which is already opened on port 2323.

package com.company;


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

public class Main {

static WebDriver driver;

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

opt.setExperimentalOption("debuggerAddress","localhost:9014");
driver=new ChromeDriver(opt);

driver.findElement(By.xpath("//*[@id='identify_email']")).sendKeys("7011516489");

}
}
***********************************************************************************************************************************************************

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



Best of Luck.

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.