0% found this document useful (0 votes)
3 views

Selenium From Window Handle

The document provides detailed instructions on handling child windows and pop-ups in Selenium, including methods to get window handles, print titles, and close specific or all browsers. It includes various Java code snippets for automating browser actions such as counting tabs, handling mouse actions, and working with frames. Additionally, it outlines exceptions encountered during automation and offers assignments for practical application of the concepts discussed.

Uploaded by

sai vivek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Selenium From Window Handle

The document provides detailed instructions on handling child windows and pop-ups in Selenium, including methods to get window handles, print titles, and close specific or all browsers. It includes various Java code snippets for automating browser actions such as counting tabs, handling mouse actions, and working with frames. Additionally, it outlines exceptions encountered during automation and offers assignments for practical application of the concepts discussed.

Uploaded by

sai vivek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Child Window Pop / Child Browser Pop Up-

Characteristics
We can move this Pop Up.
We can Inspect this Pop Up.
This Pop Up will have Minimum, Maximise and Close button along with the Address Bar.

Solutions
To handle Child Window Pop we use getWindowHandles() and switchTo().window() statement.

Note
Window Handle:- Address of the browser present on the desktop is known as Window
Handle.(session id)
In order to retrieve it we use getWindowHandle() or getWindowHandles().

Write a Script to get the Window Handle and print it on the console for google.com.

public class ChildWindowPop


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
String wh = driver.getWindowHandle();
System.out.println(wh);
driver.close();

O/P-
Cdwindow-8BF45AF68ED4E8CE1130A84D26A16EAD

Write a Script to print no. Of browsers opened by naukri.com

public class PrintCountWindows


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("http://www.naukri.com/");
Set<String> allwh = driver.getWindowHandles();
int count = allwh.size();
System.out.println(count);
driver.quit();
}

Difference between getwindowhandle and getwindowhandles

getWindowHandle getWindowHandles
It returns the address of Current Browser It returns address of all the browsers
Return Type of getWindowHandle is String Return type of getWindowHandles is
Set<String>

Write a Script to print all the address of all the browsers opened by naukri.com

public class AddressOfAllWindows


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("http://www.naukri.com/");
Set<String> allwh = driver.getWindowHandles();
int count = allwh.size();
System.out.println(count);
for(String wh:allwh)
{
System.out.println(wh);
}
driver.quit();

Write a Script to print all the Titles of the browsers opened by naukri.com

public class PrintAllTitlesNaukri


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("http://www.naukri.com/");
Set<String> allwh = driver.getWindowHandles();
int count = allwh.size();
System.out.println(count);
for(String wh:allwh)
{
driver.switchTo().window(wh);
String title = driver.getTitle();
System.out.println(title);
}
driver.quit();

**Write a Script to close all the browsers without using quit().

public class CloseAllNaukri


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("http://www.naukri.com/");
Set<String> allwh = driver.getWindowHandles();
int count = allwh.size();
System.out.println(count);
for(String wh:allwh)
{
driver.switchTo().window(wh);
driver.close
}

BACKSIDE OF COPY
NoSuchWindowException – Selenium/Unchecked
We get this Exception when ever we try perform any action on the browser which is
already closed or we pass invalid Window Handle to window().

07/12/2021
Write a Script to close this specific Browser in naukri.com

public class CloseSpecificBrowser {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}

public static void main(String[] args)


{
System.out.println("Enter the title to be closed");
Scanner sc= new Scanner(System.in);
String expectedtitle = sc.nextLine();
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
Set<String> allwh = driver.getWindowHandles();
for(String wh:allwh)
{
driver.switchTo().window(wh);
String actualtitle=driver.getTitle();
if(actualtitle.equals(expectedtitle))
{
driver.close();
}
}
}
}

ASSIGNMENT
Write to close all the browsers except the specific browser.

Write a script to close all the browsers except the parent browsers.

public class CloseAllBrowserExceptParent


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}

public static void main(String[] args)


{
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
String pwh = driver.getWindowHandle();
Set<String> allwh = driver.getWindowHandles();

for(String wh:allwh)
{
driver.switchTo().window(wh);
if(!(pwh.equals(wh)))
{
driver.close();
}
}

}
Summary Of the Pop Ups

POP UP SOLUTIONS
JavaScript/Alert Pop Up By using driver.switchTo().alert()-
accept,dismiss,getText
Hidden Division/ Calender Pop Up By using findElement()
File Upload Pop Up By using
BrowserButton.sendKeys(absolutePath).
File Download Pop Up (Firefox) By using Robot class(for Chrome Browser no
need to handle)
Print Pop Up() By using Robot Class (for Chrome Browser-
findElement())
Notification Pop Up By using addArguments() of BrowserOptions
class to change the settings
Authentication Pop Up By sending the Username and Password in
along with the URL in get().
Child Window/Browser Pop Up By using getWindowHandles() and
driver.switchTo().window() statement.

HANDLING TABS
Tab is also treated as New Window in Selenium.
Here we are going to handle the tab in the same way as we handle child window Pop or
Child Window Pop Up.

Write a Script to count the no. Of tabs present in the browser after clicking in
actiTime Link.

public class NoOfTabsInActiTimeLink


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/");
driver.findElement(By.linkText("actiTIME Inc.")).click();
Set<String> allwh = driver.getWindowHandles();
int count = allwh.size();
System.out.println(count);
driver.quit();
}

ASSIGNMENT
Write a script to print the window handles of all the tabs present in the browser after
clicking actitime link.
public class PrintAllTabActitime
{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/");
driver.findElement(By.linkText("actiTIME Inc.")).click();
Set<String> allwh = driver.getWindowHandles();
int count = allwh.size();
System.out.println(count);
for(String wh:allwh)
{
driver.switchTo().window(wh);
String title = driver.getTitle();
System.out.println(title);
}
driver.quit();
}

Write a Script to close all the tabs without using quit()

public class CloseAllTabsWithoutQuit


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/");
driver.findElement(By.linkText("actiTIME Inc.")).click();
Set<String> allTabwh = driver.getWindowHandles();
for(String tabwh:allTabwh)
{
driver.switchTo().window(tabwh);
driver.close();
}
}

How do you close the current tab?


Ans) driver.close()

How to close all the tabs?


Ans) driver.quit()

ASSIGNMENT
Write a Script to AUTOMATE the following scenario.:

1) Go to to demo.actitime.com
2) Login to the application
3) Go to Help drop down Icon(?) and select “about your actitime”.
4) Click on Read Service Agreement on the Pop Up.
5) Print all the Tab Headings present in the new Tab.

public class ActitimeReadServiceAgreement


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//div[.='Login ']")).click();
Thread.sleep(5000);

driver.findElement(By.xpath("(//div[@class='menuCellDiv']/table/tbody/tr[2]/td/di
v/div[4]/div/div/div/div)[1]")).click();
Thread.sleep(5000);
driver.findElement(By.xpath("//a[.='About your actiTIME']")).click();
driver.findElement(By.xpath("//a[.='Read Service Agreement']")).click();
Set<String> alltabwh = driver.getWindowHandles();
for(String tabwh:alltabwh)
{
driver.switchTo().window(tabwh);
String title = driver.getTitle();
System.out.println(title);
}
driver.quit();
}

08/12/2021
Write a script to close the Child tab 1st then the Parent tab by using Iterator.

public class HandlingTabs


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}

public static void main(String[] args)


{
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/login.do");
driver.findElement(By.linkText("actiTIME Inc.")).click();
Set<String> allTabwh = driver.getWindowHandles();
Iterator<String> itr = allTabwh.iterator();
String pwh = itr.next();
String cwh = itr.next();
driver.switchTo().window(cwh);
driver.close();
driver.switchTo().window(pwh);
driver.close();
}

HANDLING MOUSE ACTIONS


By using Mouse we can perform the following actions:-
1) Mouse Hover (Handling drop down menu)
2) Right Click (Context Click)
3) Drag and Drop
4) Double Click

How do you handle Drop Down Menu / Mouse Hover in Selenium?


Ans) Mouse Hover means moving the mouse pointer to a particular location. Drop Down
Menu means it is an element on which if we move the mouse pointer, it will display
the list of options. To handle drop down/ mouse hover we use moveToElement() of
Actions class.

Action is an Interface and Actions is a class.


Actions class is present in org.openqa.selenium.interactions package.

Actions class is mainly used for Mouse Actions and it has parametrized constructor
where it takes WebDriver as an argument.
Whenever we call any methods of Actions class, we have to use perform() at the
last.

All the methods present of Actions class is an example for Method Overloading.

AUTOMATE the following scenario:-


1) Open the browsers
2) Go to vtiger.com
3) Mouse hover to ‘Resource’ Tab
4) Click on Contact us in the drop down menu
5) Get the Bengaluru, India Phone No. And print it on the console.
6) Close the Browser.

public class MouseHandlingActions1


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.vtiger.com/");
driver.manage().window().maximize();
WebElement resourceTab =
driver.findElement(By.partialLinkText("Resources"));
Actions a = new Actions(driver); //passing obj ref var of type WebDriver
in Actions class
a.moveToElement(resourceTab).perform(); //perform() - execute
driver.findElement(By.partialLinkText("Contact Us")).click();
String phnno =
driver.findElement(By.xpath("//p[contains(text(),'Bengaluru')]/../p[2]")).getText();
System.out.println(phnno);
driver.close();
}
}

How do you Handle Context Click (Context Menu)?


Right clicking in mouse is called as Context Click.
When we right click on any element we get list of options which is called as Context
Menu.
To right click on any element we use contextClick() of Actions class.
To select the required options in the Context Menu we press the Shortcut Keys such as
T- New Tab, W- New Window.

Write a Script to open Actitime link in new window.

public class RightClick


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws AWTException, InterruptedException
{
WebDriver driver = new ChromeDriver();
driver.get("https://demo.actitime.com/");
WebElement link = driver.findElement(By.linkText("actiTIME Inc."));
Actions a = new Actions(driver);
a.contextClick(link).perform();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_W);
Thread.sleep(5000);
driver.quit();

How we perform drag and drop in Selenium.


By using dragandDrop() of Actions class.

Example-

URL:- http://www.dhtmlgoodies.com/submitted-scripts/i-google-like-drag-drop/index.html

Program:-

public class HandlingDragandDrop {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws AWTException, InterruptedException
{
WebDriver driver = new ChromeDriver();
driver.get("http://www.dhtmlgoodies.com/submitted-scripts/i-google-like-
drag-drop/index.html");
WebElement src = driver.findElement(By.xpath("//h1[text()='Block 1']"));
WebElement dest = driver.findElement(By.xpath("//h1[text()='Block 4']"));
Actions a = new Actions(driver);
a.dragAndDrop(src, dest).perform();
}

How do you perform Double click?


By using doubleClick() present in Actions class.
Ex:- a.doubleClick().perform

jqueryui.com
09/12/2021
AUTOMATE the following scenario:-
1) Go to vtiger.com
2) Mouse Hover to ‘Resources’ and select customers in the Drop Down Menu.
3) Click Double click on ‘Read Full Story’ button.
4) Check whether ‘HackerEarth’ page is displayed or not?

public class HackerEarth


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.vtiger.com/");
driver.manage().window().maximize();
WebElement resourceTab =
driver.findElement(By.partialLinkText("Resources"));
Actions a = new Actions(driver);
a.moveToElement(resourceTab).perform();
driver.findElement(By.partialLinkText("Customers")).click();
WebElement rfslink = driver.findElement(By.linkText("READ FULL STORY"));
a.doubleClick(rfslink).perform();
Thread.sleep(4000);
String title = driver.getTitle();
if(title.contains("HackerEarth"))
{
System.out.println("HackerEarth is Displayed");
}
else
{
System.out.println("HackerEarth is not Displayed");
}
driver.close();
}

HANDLING FRAMES(EMBEDDED WEBPAGES)


Webpage inside another webpage is called as Embedded Webpage(Frames).
Developer creates Embedded Webpage using <iframe> or <frameset>.
While Automating the element, if it is present inside the frame, we should transfer the
control into the frame using switchTo().frame() statement.

Example :- HTML Code to create for Page 1 is (frame) Page1.html:-

T1: <input type="text" id="t1"/> <br>


<iframe src="page2.html" id="f1">

HTML Code to create for Page 2 is Page2.html:-


T2: <input type="text" id="t2"/>

Write A script to enter jsp in T2 Text Box and qsp in T1 Text Box

public class HandlingFrames {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();

driver.get("file:///D:/WORKSTATION/SELENIUM/Automation/htmlcode/page1.html");
driver.switchTo().frame(0);
driver.findElement(By.id("t2")).sendKeys("jsp");
driver.switchTo().parentFrame();
driver.findElement(By.id("t1")).sendKeys("qsp");
}

NoSuchFrameException SELENIUM/Unchecked:-
We get this exception whenever we pass invalid argument to frame().
Page1.html

Page 2.html
Page 3.html

OK

yes

Write a Script to enter ac in T2 textbox and bd in T1 textbox character by character


alternatively.

public class HandlingFrames2 {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();

driver.get("file:///D:/WORKSTATION/SELENIUM/Automation/htmlcode/page1.html");
//switch the control inside the frame using string i.e id
driver.switchTo().frame("f1");
driver.findElement(By.id("t2")).sendKeys("a");
driver.switchTo().parentFrame();
driver.findElement(By.id("t1")).sendKeys("b");
WebElement frm = driver.findElement(By.xpath("//iframe"));
//switch to frame using WebElement
driver.switchTo().frame(frm);
driver.findElement(By.id("t2")).sendKeys("c");
driver.switchTo().defaultContent();
driver.findElement(By.id("t1")).sendKeys("d");
}
}
ASSIGNMENT
Write a Script to AUTOMATE the following scenario:-
1) Open the Browser
2) Go to makemytrip.com
3) Select Bangalore in ‘From’ Textbox.
4) Select Goa in ‘To’ Textbox.
5) Select the date 31st Dec, 2021 in the Depart on Calender Pop Up.
6) Click on ‘Search Flights’ button.
7) Capture and print all the flights along with departure time.

public class MakeMyTripBnglrToGoa


{
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.makemytrip.com/");
Thread.sleep(4000);
WebElement fromCity = driver.findElement(By.id("fromCity"));
Actions a = new Actions(driver);
a.doubleClick(fromCity).perform();
Thread.sleep(2000);
driver.findElement(By.xpath("//input[@class='react-autosuggest__input
react-autosuggest__input--open']")).sendKeys("Bengaluru, India");
Thread.sleep(4000);
WebElement selectFromList =
driver.findElement(By.xpath("//p[contains(text(),'Bengaluru')]"));
Thread.sleep(4000);
a.doubleClick(selectFromList).perform();
WebElement toCity = driver.findElement(By.id("toCity"));
a.doubleClick(toCity).perform();
driver.findElement(By.xpath("//input[@placeholder='To']")).sendKeys("Goa,
India");
Thread.sleep(4000);
WebElement selectToList =
driver.findElement(By.xpath("//p[contains(text(),'Goa')]"));
a.doubleClick(selectToList).perform();
WebElement clickDeptDate = driver.findElement(By.id("departure"));
a.doubleClick(clickDeptDate).perform();
Thread.sleep(2000);
a.doubleClick(driver.findElement(By.xpath("(//p[.='31'])[1]"))).perform();
Thread.sleep(2000);

a.doubleClick(driver.findElement(By.xpath("//img[@alt='MakeMyTrip']"))).perform();

Thread.sleep(2000);
a.doubleClick(driver.findElement(By.xpath("//a[.='Search']"))).perform();

List<WebElement> allflights =
driver.findElements(By.xpath("//div[@class='listingCard']/div[2]/div[1]/div/span"));
List<WebElement> allprice =
driver.findElements(By.xpath("//div[@class='listingCard']/div[2]/div[4]/div/div/p"));
List<WebElement> depttime =
driver.findElements(By.xpath("//div[@class='listingCard']/div[2]/div[2]/label/div/div/d
iv[1]/div[1]/p/span"));
int count = allflights.size();
for(int i=0;i<count;i++)
{
String flightName = allflights.get(i).getText();
String price = allprice.get(i).getText();
String time = depttime.get(i).getText();
System.out.println(flightName+"------------>"+time+"-----------
->"+price);
}
driver.close();

HANDLING DISABLED ELEMENTS AND SCROLL BAR

In Selenium, we don’t have a method to handle disabled Elements and Scroll Bar(By
using Java).
In order to handle we use executeScript().
ExecuteScript is declared in JavaScriptExecutor Interface and implemented in
RemoteWebDriver Class. Since, we already Upcasted to Browser Specific classes to
WebDriver interface, this method will be hidden. In order to access this method, we
should downcast it to RemoteWebDriver or Typecast the object to JavaScriptExecutor.

If the elements are disabled and if we try to perform action on disabled elements,
it will throw ElementNotInteractableException.

Example:-
UN:<input type=“text” id=’d1’/> <br>
PW:<input type=“text” id=“d2” disabled/> <br>
<input type=“button” value = “Login”/>

public class DisabledElementsDownCasting {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();

driver.get("file:///D:/WORKSTATION/SELENIUM/Automation/htmlcode/Disabled.html");
driver.findElement(By.id("d1")).sendKeys("admin");
RemoteWebDriver r = (RemoteWebDriver) driver;
r.executeScript("document.getElementById('d2').value='manager'");

}
Search Context

TypeCasting

WebDriver JavascriptExecutor

Down Casting

RemoteWebDriver

ChromeDriver

NOTE
In order to validate JavaScript statement in the browser, Inspect the Element and
click on Console Tab present in the Developer Toolbar and type the JavaScript
statement.

JAVASCRIPT STATEMENTS used:-

document.getElementById(‘d3’).click() - for clicking on the element.

document.getElementById(‘d2’).value=‘’ - for deleting the text present in the


textbox.
Write a Script to Scroll 3000 pixels Vertically in bbc.com
public class HandlingScrollBbc {
static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.bbc.com/");
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("window.scrollBy(0,3000)");

Write a Script to Scroll to particular element in bbc.com.

public class HandlingScrollBbc {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.bbc.com/");
JavascriptExecutor j = (JavascriptExecutor) driver;
int y = driver.findElement(By.xpath("//span[text()='Future
Planet']")).getLocation().getY();
j.executeScript("window.scrollBy(0,"+y+")");

Write a script to scroll to the bottom of the webpage in bbc.com.

public class HandlingScrollBbc {


static
{
System.setProperty("webdriver.chrome.driver",
"./driver/chromedriver.exe");
}
public static void main(String[] args)
{
WebDriver driver = new ChromeDriver();
driver.get("https://www.bbc.com/");
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("window.scrollTo(0,document.body.scrollHeight)");

j.executeScript("window.scrollTo(0,0)");

Backside of Notecopy
ElementNotInteractableException (Selenium/Unchecked):-
We get this exception whenever we try to perform action on the disabled elements().

JavascriptException (Selenium/Unchecked):-
We get this exception whenever there is a mistake in syntax of JavaScript statement.

You might also like