Monday, 22 October 2018

OOPS Concepts for Selenium - Examples to Practice


Java concepts-3 {oops concept}
Java program structure:
-----------------------
1. Class with main method:
Syntax:

package package_name;
public class class_name
  {
//declarations
pubic static void main (String[] args)
{
--------------
--------------//statements
}
  }

Under main method, script will execute that has written under main method only

2. Class with multiple methods:

In general, within a Class we can create multiple methods/functions

Advantages:
-reusability of the script within the class or another class
-script is easy to understand
-easy to idenitfy any logical errors

There are 2 types of methods/functions in a class
a. Static method:
b. Non-static method:

a. Static methods:
When we create methods with "static" keyword, we can call those methods
directly into main method using name of the method (i.e. static method)

Syntax:{class with multiple static methods}

package package_name;
public class class_name{
//declarations
public static void methodOne(){
---------
---------//statements
}
public static void methodTwo(){
----------
----------//statements
}

public static void main (String[] args){
//method calling
}
}


Exp: Write a program to perform different arithmetic operations using static methods in a class


package oops.concepts;

public class ArithemeticEx {
public static int result; //declare class level variable to use it throughout the class
//creating a method to reuse in main method
public static void Addone(){
int a= 10;
int b= 20;
result= a+b;
System.out.println("Addition of given values is: "+result);
}

//creating a method to reuse in main method
public static void multiTwo(){
int x= 10;
int y= 20;
result= x*y;
System.out.println("multiplication of given values is: "+result);
}

public static void main(String[] args) {
//calling methods created above in main method
Addone();
multiTwo();

}

}


2. Non-static methods:
Currently, this method is widely used

Syntax:{to create Non-static methods}
public void methodName(){
------
------} Script
}

To call a non-static method into main method, we need to create instance object
for the class

Syntax: {to create Instance object for Class}
class_name obj= new class_name();
//to call non-static methods
obj.method_name();

NOTE:  A static method belongs to the class and a non-static method belongs to an object

Static methods are useful if you have only one instance where you're going
to use the method, and you don't need multiple copies (objects).

Non-static methods are used if you're going to use your method to create
multiple copies


Exp: Write program to perform different arithmetic operations using non-static methods

package oops.concepts;

public class ArithemeticEx {
public int result;

public void Addone(){
int a= 10;
int b= 20;
result= a+b;
System.out.println("Addition of given values is: "+result);
}

public void multiTwo(){
int x= 10;
int y= 20;
result= x*y;
System.out.println("multiplication of given values is: "+result);
}

public static void main(String[] args) {
//create instance object for class
ArithemeticEx AE= new ArithemeticEx();

//to call sub methods
AE.Addone();
AE.multiTwo();

}

}
---------------------------------------------------------------------------------------------------
Difference between non-static and static methods

Non-static method Static method
1.Memory is allocated as many time as method Memory is allocated only once at the time of class loading.
is called

2. It is specific to an object, these These are common to every object, it is also known
are also known as instance method. as member method or class method.

3.These methods always access with object reference This property always access with class reference
Syntax: Syntax:
Objref.methodname(); className.methodname();

4.if any method wants to be execute multiple times If any method wants to be execute only once
that can be declare as non static. in the program that can be declare as static

-------------------------------
Passing values to submethods:
-------------------------------
in general we should not maintain any fixed values/hard coded
values in sub methods
whereas we pass the values/data to the submethods
while calling those methods from main method
to read values from main method, sub method should have arguments
syntax:
public void methodName(arg1, arg2)
{
-------
-------//statements
}

Exp: Create class with submethod to pass the values from main method


package oops.concepts;

public class ArithemeticEx {
public int result;

public void Addone(int a, int b){

result= a+b;
System.out.println("Addition of given values is: "+result);
}

public void multiTwo(int x, int y){

result= x*y;
System.out.println("multiplication of given values is: "+result);
}

public static void main(String[] args) {
//create instance object for class
ArithemeticEx AE= new ArithemeticEx();

//to call sub methods
AE.Addone(5, 6);
AE.multiTwo(9, 5);

}

}


Exp: Write a program to click on different language links in Google home page
using non-static method

package oops.concepts;

import java.util.concurrent.TimeUnit;

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

public class GoogleLang {
public WebDriver driver;
public void setUp(){
driver= new FirefoxDriver();
driver.get("http://google.co.in");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

public void langClick(String myLang) throws InterruptedException{
driver.findElement(By.linkText(myLang)).click();
Thread.sleep(3000);
}

public void tearDown(){
driver.quit();
}
public static void main(String[] args) throws InterruptedException {
GoogleLang gl=new GoogleLang();
gl.setUp();
gl.langClick("??????");
gl.langClick("?????");
gl.langClick("English");
gl.tearDown();


}

}

----------------------------
Return value by submethod:
----------------------------
We can use "return" keyword in sub method and specify data type in place of "void"

Syntax:
public data_type subMethod(){
----
----//statements
return value;
}

Exp: Write program to perfrom arithemetic operation, to call submethod we need to pass the test data,
and also submethod should return the value to main method

package oops.concepts;

public class ArithemeticEx {
public int result;

public int Addone(int a, int b){

result= a+b;
return result;
}

public int multiTwo(int x, int y){

result= x*y;
return result;
}

public static void main(String[] args) {
//create instance object for class
ArithemeticEx AE= new ArithemeticEx();

//to call sub methods
int m=AE.Addone(5, 6);
int n=AE.multiTwo(9, 5);
System.out.println("addition of 5 and 6 is: "+m);
System.out.println("multiplication of 9 with 5 is: "+n);

}

}
--------------------
Method overloading:
--------------------

When we have more than one method with same name within the class is called Method overloading

It can differ based on:
-number of arguments in a method
-Data type of arguments
-sequence of data type of arguments

Exp:
public class MethodOL {
public void demoOne(int a, int b){
int c= a*b;
     System.out.println("multiplication of given values is: "+c);
}

public void demoOne(String x, String y){
String z= x+y;
System.out.println(z);
}

public static void main(String[] args) {
MethodOL ml= new MethodOL();
ml.demoOne(5, 6);
ml.demoOne("InsightQ", "Technologies");

}

}

-------------
Constructor:
-------------

Constructor will automatically execute whenever we created instance object for Class

rules:
-constructor name is same as Class name
-should not use "void" in Constructor

NOTE:  In general Constructors are used to initialize values into variables

Exp:

public class ConstEx {

public ConstEx(){
System.out.println("this is sample script");
}

public static void main(String[] args) {

ConstEx ce= new ConstEx();

}

}

--------------------------
Constructor Overloading:
--------------------------

A class having more than one Constructor is called Constructor overloading

Constructors can be differ based on argument list

Exp:
public class ConstEx {

public ConstEx(int a, int b){
int c= a*b;
      System.out.println("multiplication of given values is: "+c);
}
public ConstEx(String x, String y){
String z= x+y;
System.out.println(z);
}

public static void main(String[] args) {

ConstEx ce= new ConstEx(5,6);
ConstEx cex= new ConstEx("Mindq","Systems");
}
}

--------------
Inheritance:
--------------

Acquiring properties from one class to another class is called Inheritance

Parent class:
Parent class, also called as base class/super class.
The class methods that are called into another class is called parent class

Child class:
The class that acquires methods from another class is called
  Child class/derived class/extened class

extends Keyword:
extends is the keyword used to inherit the properties of other parent class
into child class

Syntax:
public class ChildClass extends ParentClass{

}

Exp:

Step 1: Create parent class {i.e. ParentClass} with 2 submethods and without
main method (i.e. non-executable class)

Script:
package oops.concepts;

public class ParentClass {

public void login(){
System.out.println("setup program");
}

public void tearDown(){
System.out.println("it is logout program");
}

}

Step 2: Create child class with "extends" keyword

extends Keyword:  extends is the keyword used to inherit the properties of other class


Exp:

Script:
package oops.concepts;

public class ChildClass extends ParentClass{

public static void main(String[] args) {
ChildClass cc= new ChildClass();
cc.login();
cc.tearDown();
}

}


--------------------
Method overriding:
--------------------

Means same method having in Parent class as well as childclass

Exp: 
package oops.concepts;

public class ChildClass extends ParentClass{
public void login(){
System.out.println("setup program2");
}

public static void main(String[] args) {
ChildClass cc= new ChildClass();
cc.login();
cc.tearDown();
ParentClass pp= new ParentClass();
pp.login();

}

}

------------------------------
Super keyword in Overriding:
------------------------------

Super keyword is used for calling the parent class method/constructor in child class

Syntax: super.methodname() will call the specified method of base class
and super() calls the constructor of base class

Exp:
public class MyChildClass extends MyBaseClass{

public void setUp(){
System.out.println("Login with Invalid data");
super.setUp();
}

public static void main(String[] args) {
MyChildClass mcc= new MyChildClass();
mcc.setUp();
mcc.tearDown();

MyBaseClass mbc= new MyBaseClass();
mbc.setUp();
}
}

Saturday, 20 October 2018

Exception Handling in Selenium - Examples to Practice

Exception Handling:

There are 2 types of exceptions

Usually, exceptions are classified as problems that happens during execution

i. Compile time exceptions
ii. Runtime exceptions

i. Compile time Exceptions: These are 2 types:
a.Syntax errors:
Exp: String a; (Correct)
Stng a; (Incorrect)

b.Semantic errors
Variables may declared twice
Exp: int a; (Once Correct)
----
----
int a; (Twice incorrect)

NOTE:  By Default these are highlighted in red in Eclipse while writing the script


ii.Runtime exceptions:

These are interruptions that happens during program execution time.
A good program should handle all the exceptions and continue with its
normal flow of program execution.

Exception Handle is a set of code that handles an exception
Exceptions can be handled in Java using "try & catch" block of code

Sytanx:{for- try & catch}

try{
        statement(s)
      }
      catch (Exception exception_name){
        statement(s)
      }

NOTE: The "finally" block is executed irrespective of an exception being raised in
  the try block.

It is optional to use with a try block

Syntax: {try & catch with finally}
try{
      statement(s)
      }
      catch(Exception Exception_name){
        statement(s)
      }
      finally{
        statement(s)
      }


Exp:
Scanner sc=new Scanner(System.in);
System.out.println("please enter the value:");
  int b=sc.nextInt();

try{
int a=10;
        int c=a/b;
        System.out.println(c);
}catch(Exception e)
{
System.out.println("dont pass b value as:"+b);
//e.printStackTrace();//it notifys the exception location
}
finally{
System.out.println("SampleSelenium");
}

Exp:

  try {
  int a=10;
  int b=0;
  //int b=2; (switch between two b values to get different outcome)
  int c=a/b;
  System.out.println(c);
  }
  catch (Exception x){
  System.out.println("b-value should not be zero");
  System.out.print(x);
  }
  finally{
  System.out.print("This is an Example of an exception Handling");
  }


Wednesday, 17 October 2018

Javascript Executor for Selenium - Examples to Practice

JavascriptExecutor:
===============

JavaScriptExecutor is an interface class, which is provided in
WebDriver library similar to Actions, Select...etc

Using this class we can click on a webelement, enter data,
highlight a specific webelement, scroll down page...etc

JavascriptExecutor is providing "executeScript" method to perform operations

Exp: Write script to open specified url using JavascriptExecutor

WebDriver driver= new FirefoxDriver();
//type casting
JavascriptExecutor js= ((JavascriptExecutor)driver);
//to open url
js.executeScript("window.location='http://login.salesforce.com'");


Exp: Write script to enter a value in Email edit box using javascriptExecutor

WebDriver driver= new FirefoxDriver();
driver.get("http://login.salesforce.com");
driver.manage().window().maximize();

JavascriptExecutor js= ((JavascriptExecutor)driver);

js.executeScript("window.document.getElementById('username').value='InsightQ'");


Exp: Write script to get popup window

WebDriver driver= new FirefoxDriver();

JavascriptExecutor js= ((JavascriptExecutor)driver);

//Create popup message using javaScript Executor
js.executeScript("window.alert('Hi, I am executing Webdriver')");
Thread.sleep(3000);
driver.switchTo().alert().accept();


Exp: Write script to highlight "username" edit box

WebDriver driver= new FirefoxDriver();
driver.get("https://login.salesforce.com");
driver.manage().window().maximize();

WebElement ele1= driver.findElement(By.id("username"));
JavascriptExecutor js= ((JavascriptExecutor)driver);
js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px dashed red;');", ele1);

NOTE:  Style of border eg; dahed, dotted, solid, doubles, groove...etc

Exp: Write script to find size of window

WebDriver driver= new FirefoxDriver();
driver.get("http://www.rediff.com/");
driver.manage().window().maximize();

JavascriptExecutor js= ((JavascriptExecutor)driver);

//to find size of window
long height= (long)js.executeScript("return window.innerHeight");
long width= (long)js.executeScript("return window.innerWidth");
System.out.println("Height is: "+height);
System.out.println("Width is: "+width);

Exp: Write script to scroll down the page
WebDriver driver= new FirefoxDriver();
driver.get("http://www.rediff.com/");
driver.manage().window().maximize();

JavascriptExecutor js= ((JavascriptExecutor)driver);

//to scroll down
js.executeScript("window.scrollBy(0, 1500)");
Thread.sleep(2000);
//to scroll up
js.executeScript("window.scrollBy(0, -1500)");
Thread.sleep(2000);


Exp:

public class JavaSCriptExecutor {

public WebDriver driver;

public void openURL() throws Exception{

driver = new FirefoxDriver();
        driver.get("https://www.youtube.com/watch?v=6SRQQ1jdBJw");
        driver.manage().window().maximize();
        Thread.sleep(10000);
     
}

public void executor() throws Exception{
JavascriptExecutor js = (JavascriptExecutor)driver;
Thread.sleep(10000);
js.executeScript("document.getElementById('movie_player').pauseVideo();");
Thread.sleep(5000);
js.executeScript("document.getElementById('movie_player').playVideo();");
Thread.sleep(5000);
js.executeScript("document.getElementById('movie_player').seekTo(50);");
Thread.sleep(5000);
js.executeScript("document.getElementById('movie_player').pauseVideo();");
Thread.sleep(5000);
js.executeScript("document.getElementById('movie_player').seekTo(10);");
Thread.sleep(5000);
js.executeScript("document.getElementById('movie_player').playVideo();");
Thread.sleep(10000);
driver.quit();
}

public static void main(String[] args) throws Exception {
JavaSCriptExecutor j = new JavaSCriptExecutor();
j.openURL();
j.executor();

}
}

Thursday, 11 October 2018

ToolTips and CaptureScreenShot - Examples to Practice


Reading Tooltip:
============
Exp: Create script to read Tooltip from google logo

Script:
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");

WebElement googleImage = driver.findElement(By.id("hplogo"));

String googleImageToolTip = googleImage.getAttribute("title");
System.out.println(googleImageToolTip);


Capturescreenshot:
==============

Using “TakesScreenshot" Interface we can Capture Screenshot of a page

Exp: Write script to capture snapshot of www.facebook.com home page

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");


File f= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f, new File("E:\\demo134.png"));
//to maintain in our working folder
FileUtils.copyFile(f,new File("./Screenshot/demo.png"));

Working on Drag n Drop in WebDriver - Examples to Practice


Working on DragAndDrop:
====================
  To perfrom drag and drop operations we can use "Actions" class

Syntax:
Actions act = new Actions(driver);
act.dragAndDrop(ele1, ele2).build().perform();

Exp: Write script to perform drag and drop operation in "http://jqueryui.com/droppable/"


WebDriver driver= new FirefoxDriver();
driver.get("http://jqueryui.com/droppable/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.switchTo().frame(0);
WebElement ele1=driver.findElement(By.id("draggable"));
WebElement ele2=driver.findElement(By.id("droppable"));

Actions act= new Actions(driver);
act.dragAndDrop(ele1, ele2).build().perform();

Exp: Create script to DragAndDrop "Daily Deals" in http://ebay.in

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://ebay.in");

Thread.sleep(10000);

Actions act = new Actions(driver);
WebElement ele1 = driver.findElement(By.id("gh-btn"));
WebElement ele2 = driver.findElement(By.xpath("//h2[text()='Daily Deals']"));
act.dragAndDrop(ele1, ele2).build().perform();

Working on Action Class in WebDriver - Examples to Practice

Working on Actions class:
====================
In Webdriver, We can use "Actions" Class to handle keyboard events, mouse events, mouse
hovers, Drag & Drop and click operations

Syntax:{to Configure Actions class}

Actions act = new Actions(driver);

// To click on webelement using Actions class:
Firstly, we need to specify webelement location and then specify operation that needs to perform

Syntax:
act.moveToElement(element).click().build().perform();

NOTE: We need to use perform() to execute the specified action

Exp: Write script to right click (i.e. Context click) on search edit box in www.amazon.in

Script:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://amazon.in");

WebElement search= driver.findElement(By.id("twotabsearchtextbox"));
Actions act= new Actions(driver);
act.moveToElement(search).contextClick().build().perform();

Exp: Write script to enter "selenium" in upper case at search edit box
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://amazon.in");

WebElement search= driver.findElement(By.id("twotabsearchtextbox"));
Actions act= new Actions(driver);
Thread.sleep(3000);

act.moveToElement(search).click().keyDown(Keys.SHIFT).sendKeys("smallerletters").build().perform();

Exp: Write script to select "wish list" in amazon.co.in
WebDriver driver= new FirefoxDriver();
driver.get("http://amazon.in");
//create Actionclass
Actions ac= new Actions(driver);
WebElement signIn= driver.findElement(By.xpath("//span[text()='Hello. Sign in']"));
WebElement submenu= driver.findElement(By.xpath("//span[text()='Your Wish List']"));
ac.moveToElement(signIn).moveToElement(submenu).click().build().perform();

Exp: Write script to click "frequently asked questions" option in "Customer care" menu
WebDriver driver= new FirefoxDriver();
driver.get("http://hdfcbank.com");
driver.manage().window().maximize();
Actions act= new Actions(driver);
act.moveToElement(driver.findElement(By.linkText("Customer Care"))).build().perform();
Thread.sleep(2000);
driver.findElement(By.linkText("Frequently Asked Questions")).click();

Working on Keyboard Events in WebDriver - Example to Practice

Working on Keyboard Events Using SendKeys();
====================================

Using sendkeys() method we can perform keyboard operations on webelement

Syntax: WebElement.sendKeys(Keys.event);

Exp: Write script to select 3rd option in Google search after enter "Selenium"
in search box without using locator value for that option

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://google.co.in");

WebElement we=driver.findElement(By.id("lst-ib"));

we.sendKeys("selenium");
Thread.sleep(2000);
we.sendKeys(Keys.ARROW_DOWN);
we.sendKeys(Keys.ARROW_DOWN);
we.sendKeys(Keys.ENTER);

Working with Calendar on WebDriver - Examples to Practice

Working on "Calendar"
=================
To select a date element in calendar we can use click() method

Exp: Write script to select date in 2nd month of Calendar
  from url:https://www.justdial.com/travel/train-booking

Script:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.justdial.com/travel/train-booking");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


driver.findElement(By.id("frm_stn")).sendKeys("Hyd");
driver.findElement(By.linkText("Hyderabad Kacheguda (KCG)")).click();

driver.findElement(By.id("to_stn")).sendKeys("NLR");
driver.findElement(By.linkText("Nellore (NLR)")).click();


driver.findElement(By.xpath("//div[@id='ui-datepicker-div']/div[2]/table/tbody/tr[4]/td[6]/a")).click();


Exp: Write script to select Dec 16th in Calendar

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://makemytrip.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.findElement(By.id("hp-widget__depart")).click();


while(true){
String myMonth=driver.findElement(By.xpath("//div[@class='ui-datepicker-title']")).getText();
System.out.println(myMonth);
if (myMonth.equals("DECEMBER 2018")){
driver.findElement(By.linkText("16")).click();
break;
}else
{
driver.findElement(By.xpath("//*[text()='Next']")).click();
}
}

Monday, 8 October 2018

Working on Multiple Windows on a Browser - Example to Practice

Working on Multiple Windows in a Browser:
=================================
To work on multiple windows we need to switch between windows by using window handles

Procedure:
Step 1: Firstly, we need to get window handles using "getWindowHandles()" command

Syntax:
Set pageHandles=driver.getWindowHandles();

It will return handles of all opened windows into a "Set" class

Step 2: Use Iterator class to read each window handle from "Set" class

Syntax:
Iterator winHandles= pageHandles.iterator();

Step 3: Rread each window handle into variable using Iterator class

Syntax:
String win1= winHandles.next();
String win2= winHandles.next();

Step 4:  To work on specified window we can use the following command:

driver.switchTo().window(window handle);

NOTE:  If we want to come back to first window, we can use below command

driver.switchTo().defaultContent();

Exp: Write script to read page titles while navigating between multiple windows

Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://accounts.google.com/signin");
driver.manage().window().maximize();

//to read first window title
String pgTitle1=driver.getTitle();
System.out.println("1st page title is: "+pgTitle1);

//to click on Help
driver.findElement(By.linkText("Help")).click();

Thread.sleep(3000);
//to read opened window handles
Set pgHandles=driver.getWindowHandles();
//to read each window handle
Iterator winHandles=pgHandles.iterator();
//to read window handle into variable
String win1=winHandles.next();
String win2=winHandles.next();

System.out.println(win1);
System.out.println(win2);
//to focus on 2nd window
driver.switchTo().window(win2);
//to read second window title
String pgTitle2=driver.getTitle();
System.out.println("2nd page title is: "+pgTitle2);

Working on Frames in WebDriver - Examples to Practice

Working on Frames:
===============
Frame is an html document which is embedded into another
html doc (i.e. page within a Page)

Advantage of Frames is that we can update any code within a frame without impacting other code on page

Q: How to findout if a webElement is present within a Frame or not?
Right click on webelement, if we get "This frame" option
that means the webelement is present within a frame

or

if that webelement is existing under "frame" or"iframe" tag


Exp: Write script to find number of frames present in a page and to read each frame name

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html");
driver.manage().window().maximize();

//to find number of Frames in a page
List frames=driver.findElements(By.tagName("frame"));
System.out.println("Number of Frames are: "+frames.size());

//to read each frame name
for(WebElement frame: frames){
System.out.println(frame.getAttribute("name"));
}



Q: How to work on a Webelement within a Frame?
Firstly, we need a "switch" get into the frame, then we can specify
operation on webElement within that frame
We can switch between frames by using below commands.

i. driver.switchTo().frame(name/Id);
Name property or ID property of the frame.
Name is most suggested locator to identify a frame

ii. driver.switchTo().frame(index);
  Index means, if we have 3 frames in a page to identify those frames
    index will be - 0,1,2


Exp: Write script to click on "org.openqa.selenium.chrome" link under "classFrame" frame

WebDriver driver= new FirefoxDriver();
driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html");
driver.manage().window().maximize();

driver.switchTo().frame("classFrame");
driver.findElement(By.linkText("org.openqa.selenium.chrome")).click();


Exp: Write script for following scenario

-open application "https://netbanking.hdfcbank.com"
-click on "continue" button
-read msg from alert
-close alert
-enter "123456" in Userid edit box
-close browser

Script:
WebDriver driver = new FirefoxDriver();
driver.get("https://netbanking.hdfcbank.com");
driver.manage().window().maximize();

//to switch to frame
driver.switchTo().frame("login_page");

//to click on "Continue"
driver.findElement(By.xpath("//img[@alt='continue']")).click();

Thread.sleep(3000);
//to read msg from popup
String eMsg=driver.switchTo().alert().getText();
System.out.println(eMsg);

//to close popup
driver.switchTo().alert().accept();

//to enter value in editbox
driver.findElement(By.name("fldLoginUserId")).sendKeys("123456");

//to close browser
driver.quit();

Handling Popups/Alerts in WebDriver - Examples to Practice

Handling Popups/Alerts
==================

Alerts are also called as Popups/Confirmation Box/Prompt/Authentication Box
There are two types of alerts:
1. Web based alerts/popups
2. Windows based alerts/popups

1. Handling web based popups
-------------------------------------
There are 2 types of web based popups
a. HTML popups
b. Java popups

a. HTML popups:
which are developed in HTML
To handle these type of popups widnow webelements, we can script directly
to perform operation


Exp: Write script to select "6E Senior citizen" checkbox and to close
html popup(url: https://goindigo.in)

Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://goindigo.in");
driver.manage().window().maximize();

//to select "6E Senior citizen"
driver.findElement(By.xpath("//*[@id='oneWay']/form/div[1]/div/div/ul/li[3]/div/label")).click();

Thread.sleep(3000);
//to click on "OK" on popup window
driver.findElement(By.xpath("//*[@id='globalModal']/div/div/div[3]/button")).click();


b. handling Java popups:
if firebug is not showing any html code then it is considered as Java popup
To handle Java popups we use "Alert" class

Syntax: {to create instance object for Alert class}
Alert alt= driver.switchTo().alert();

We can use following commands to work on Alerts
i. alt.accept();
to accept alert(i.e. to click on "OK")
ii. alt.getText();
to read alert message
iii. alt.dismiss();
it will dismiss the alert (i.e. to click on "Cancel")
iv. alt.sendkeys(value);
it will enter text into prompt/edit box on popup window


Exp: Write script for following scenario:
 
Open application (https://secure.aponline.gov.in)
Enter user id
Click on "Enter" button
Read msg from popup window
Close popup window
Enter pwd

Script:
//open application (https://secure.aponline.gov.in)
WebDriver driver= new FirefoxDriver();
driver.get("https://secure.aponline.gov.in");
driver.manage().window().maximize();
//enter user id
driver.findElement(By.id("userId")).sendKeys("Madhukar");
//click on "Enter" button
driver.findElement(By.id("ImageButton1")).click();

Thread.sleep(5000);

//create object for Java alert
Alert alt= driver.switchTo().alert();
//read msg from popup window

String eMsg=alt.getText();
System.out.println(eMsg);
//close popup window
alt.accept();
//enter pwd
driver.findElement(By.id("password")).sendKeys("mercury");



2. Handling windows based alerts/popups:{uploading file}
Selenium does not support windows based popups directly

Exp:  Print popup window or browsing a file while uploading a file.
To handle windows based pop-ups there are several 3rd
party tools available eg., AutoIT, sikuli...etc
There is also a java class caleed Robot Class to handle a windows based popups

Robot Class:
=========
**Robot class is a java based utility which emulates the
keyboard and mouse actions irrespective of the environment of object

Syntax: {to create instance object for Robot class}
Robot rb= new Robot();

Exp:  Create script to upload a file on "https://www.sendfiles.net/" using Robot class

Script: WebDriver driver= new FirefoxDriver();
driver.get("https://www.sendfiles.net/");
driver.manage().window().maximize();

//to click on "START NOW"
driver.findElement(By.linkText("START NOW")).click();
//to click on "Add Files"
driver.findElement(By.xpath("//span[text()='Add Files']")).click();

Thread.sleep(5000);

//to assign file path
StringSelection myFile= new StringSelection("E:\\sam.doc");
//to set vaue into system clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(myFile, null);

//create object for Robot class
Robot rb= new Robot();
//to perform Ctrl+V
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);

rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);

Thread.sleep(3000);

//to perform TAB
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);

Thread.sleep(3000);

//to perform TAB
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);

Thread.sleep(3000);

//to perform TAB
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);


OR

WebDriver driver = new FirefoxDriver();
driver.get("https://www.sendfiles.net/");

driver.findElement(By.linkText("START NOW")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[@id='uploader_browse']/span[2]")).click();
Thread.sleep(3000);
StringSelection myFile= new StringSelection("E:\\Madhukar.docx");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(myFile, null);

Robot rb= new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(5000);
rb.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(1000);
rb.keyRelease(KeyEvent.VK_ENTER);


Exp: Write script to automate follwoing Scenario

Open application “https://www.gmail.com”
Enter valid Email (seleniumuser15)
Click on "Next"
Enter valid password (Mercury9)
Click on "compose" button
Enter "To" mail id
Enter subject as "Upload File"
Click on the "attachment" icon
Enter the file path in popup window
Click on "enter" button in keyboard using Robot Class to upload a file
Click on "Send" button
Click on Account name icon
Click on "Signout"


Script:

// initialize browser and open gmail
WebDriver driver= new FirefoxDriver();
driver.get("http://gmail.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

//to perform login operation
driver.findElement(By.id("identifierId")).sendKeys("seleniumuser15");
driver.findElement(By.xpath("//*[text()='Next']")).click();

driver.findElement(By.name("password")).sendKeys("Mercury9");
driver.findElement(By.xpath("//*[text()='Next']")).click();

Thread.sleep(5000);
String pgTitle= driver.getTitle();
if (pgTitle.contains("seleniumuser15")){
System.out.println("Successful login operation");
}
else{
System.out.println("Unsuccessful login operation");
}
//compose mail
driver.findElement(By.xpath("//*[text()='COMPOSE']")).click();
Thread.sleep(2000);
//-enter "To" mail id
driver.findElement(By.name("to")).sendKeys("Selenium1234@yopmail.com");
//-enter subject
Thread.sleep(2000);
driver.findElement(By.name("subjectbox")).sendKeys("Uploading file");
//-attach file
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@class='a1 aaA aMZ']")).click();
Thread.sleep(4000);

//to select path of file
StringSelection myFile= new StringSelection("E:\\sam.doc");
//to set path of file into system clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(myFile, null);

//create instance object for robot class
Robot rb= new Robot();

//to press Ctrl+V
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);

rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);

Thread.sleep(3000);
//to operate TAB
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);

Thread.sleep(3000);
//to operate TAB
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(3000);

//to click on Enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);

Thread.sleep(5000);
//-send mail
  driver.findElement(By.xpath("//*[text()='Send']")).click();
//signout
Thread.sleep(5000);
driver.findElement(By.xpath("//*[@class='gb_7a gbii']")).click();
Thread.sleep(3000);
driver.findElement(By.linkText("Sign out")).click();



AutoIT:
======
AutoIT v3 is also freeware. It is used to perform mouse movements,
keystrokes on windows based controls
to upload/download a file using selenium webdriver we need three tools:
1. Selenium Webdriver
2. Element identifier (AutoIT window info)
3. AutoIT editor(sciTE-lite)


Download and install AutoIT:
Navigation:
Enter url: "https://www.autoitscript.com/site/autoit/downloads"
Click on 'AutoIT' Downloads option 
Download "AutoIT" by clicking on 'Download AutoIT' button
Install AutoIT (i.e. RUN)
click on "Download Editor"
Run the Downloaded file


Exp: Create script to upload file using AutoIT on www.sendfiles.net page

Procedure:
Step 1: Create script in Eclipse to open application and click to upload file
Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://www.sendfiles.net/");
driver.manage().window().maximize();

driver.findElement(By.linkText("START NOW")).click();
driver.findElement(By.xpath("//*[text()='Add Files']")).click();


Step 2: Create script in AutoIT Editor
Script:
;to wait until popup window to activate
WinWaitActive("File Upload")
;to enter file path
ControlSetText("File Upload","","Edit1","E:\Sample.docx")
;to pause execution
Sleep(2000)
;to click on open
ControlClick("File Upload","","Button1")


Step 3: Save autoIT Editor script and compile
Navigation:
select AutoIT file (.au3)
right click on mouse
select "compile (64/86)"

Step 4: Run AutoIT complied file (.exe file) AutoIT script  file by calling into Eclipse
Syntax:
Runtime.getRuntime().exec(path of .exe file);


========================================================================
Script in Eclipse:
WebDriver driver= new FirefoxDriver();
driver.get("https://www.sendfiles.net/");
driver.manage().window().maximize();

driver.findElement(By.linkText("START NOW")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[@id='uploader_browse']/span[2]")).click();
Thread.sleep(2000);
Runtime.getRuntime().exec("E:\\UploadFileEx.exe");