Switch_To Commands

SwitchTo command in selenium helps the user to navigate to or to switch the controls of the selenium in to target object.

By changing the control to the target object, we will lose the control over the previous object.

SwitchTo helps to move the control over below items:
1. Element
2. Alerts
3. Frames
4. Tabs
5. Windows.

Alerts in Selenium Python

An alert in webpage used to get the attention of the user to perform some operation on the alert or on the webpage, sometimes alerts expects input from the user.

All the alerts are formed using javascript inside HTML page, there are three kind of alerts in HTML.

Alerts takes the focus away from the current window, and forces the browser to read the message.
Alert prevents the user from accessing other parts of the web page until the box is closed.

Alert Types :
1. Alert
2. Confirmation dialog
3. Prompt

Properties of Alerts with respect to Selenium Webdriver
1. We cannot identify alerts using inspect tools
2. We cannot write xpaths for alerts
3. It is not a Window
4. We cannot handle alerts using javaScript Executor.
We can consider as not alert if any of the above property mismatches.

Code of Alert handling in selenium webdriver


When alert is present on webpage we cannot proceed further without handling the popup, and if we try to perform any operation it throws selenium.common.exceptions.UnexpectedAlertPresentException.

We can handle alerts using switch_to_alert() method present in selenium python, with help of this switch_to_alert() method we can handle the alerts created using javascript.


Syntax to handle Alert


                        		ale = driver.switch_to_alert();
                  

With this alerts api we can perform below opertaions on the pop up.
1. Accept the popUp by clicking OK button


                        		ale.accept();
                  


2. Dismiss the popUp by clicking 'X' icon.


                        		ale.dismiss();
                  


3. Get popUp text by getText method


                        		ale.text;
                  


4. Send text to popUp by send_keys (Applicable for Prompt only)


                        		ale.send_keys("test Text");
                  


Note : Selenium bindings never clicks Cancel button on any kind of alert

When does alerts occurs on a page : It can occur on a page on any time but most of the it happens on below timing of the webpage
1. On Webpage Load
2. On Webpage close
3. On click of a element
4. On Right click (when right click disabled)
5. On wrong entry of a field
6. On saving of information

Technical Tip : Now days developers are using overlays/hidden division popups rather than javascript popups

Alert

The alert() method displays an alert box with a message and an OK button, alert box is often used to inform a user about a partcular operation like details saved in Database, right click disabled, Loaded successfully such kind of messages.

Alert is formed using alert("message") in javascript, alert considers same irrespective of user operation whether he clicks OK or 'X' icon.

Alert's sole purpose is to inform user, nothing more.

Alert on Different browsers
Chrome: alert-on-chrome-selenium-webdriver

Firefox alert-on-firefox-selenium-webdriver

1. Open Url : https://chercher.tech/java/practice-pop-ups-selenium-webdriver
2. Click on Alert button, application throws an Alert box 3. Switc to the alert using driver.switchTo().alert(), we save this object in Alert type variable 'ale'
4. We can accept the alert by using accept() non-static method from the alert api, this closes the popup.


def test_open_alerts(self):
	driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
	driver.get("https://chercher.tech/java/practice-pop-ups-selenium-webdriver");
	driver.find_element_by_name("alert").click();
	ale = driver.switch_to_alert()
	# clicks 'OK' button
	ale.accept();
										


5. We can dismiss the popup using dismiss() method from alert api, this click 'X' icon on popup. (if you have performed step 4, you cannot perform this step as pop up is closed in step 4 itself)


ale = driver.switch_to_alert();
# clicks 'x' icon
ale.dismiss();
								


6. We can get the text from the pop up using text, if you have performed step 4 or 5, this step will not work


ale = driver.switch_to_alert();
# clicks 'x' icon
ale.text;
								

get-text-alert-selenium-webdriver

Confirmation Box

Confirmation box is second kind of alert, it displays a dialog with OK and Cancel button

Confirmation box informs developer about user choice whether user pressed OK or Cancel. The confirm() method returns true if the user clicked "OK", and false otherwise('X' icon and 'Cancel') to developer.

Confirmation box confirm-chrome-selenium-webdriver

We can handle Confirmation box in selenium webdriver like alert box, there is no coding difference.

Prompt

Prompt is used to get value from the user in text format. Prompt provides textbar for user input, Prompt is rarly used alert type.

Prompt : prompt-selenium-webdriver

Prompt also follows same coding as alert and prompt except sendkeys method, we can send text to prompt textbar using sendkeys() method in alerts api.

Note : You cannot use Keys.ENTER or such kind of keys with send_keys() method of alerts


driver.get("https://chercher.tech/java/practice-pop-ups-selenium-webdriver");
driver.find_element_by_name("prompt").click();
ale = driver.switch_to_alert();
ale.send_keys("chercher.tech");
										

Complete code to handle Alerts


driver.get("https://chercher.tech/java/practice-pop-ups-selenium-webdriver");
driver.find_element_by_name("prompt").click();
ale = driver.switch_to_alert();
ale.send_keys("chercher.tech");
										

What is Frame ?

We can handle frames/iframes present in the webpage using driver.switch_to command in selenium webdriver. Frame/iFrame is nothing but another webelement in html page, which displays another part of webpage.

If you take a look at the DOM structure of a page that contains an iframe you will never find inner content of the iframe. And you won't be able to interact with it via the DOM. We have to switch into frame to see the elements present in the frame.

Below frame page is present at : http://chercher.tech/practice/frames-example-selenium-webdriver frames-example-selenium-webdriver

Difference between Frames and iFrames

Both Frame and iFrame are treated similar manner with Selenium webdriver, Selenium doesnot differentiate them, so e can handle both of them in same way.

Frame is a HTML tag and used to divide the same web page or same domain into various frames/windows. Used as <frame> tag, it specifies each frame within a frameset tag. Frames are used along with frameset, frameset contains the multiple frames.


<frameset rows = "10%,80%,10%">
	<frame id= "first" name = "top" src = "/html/top_frame.htm" />
	<frame name = "main" src = "/html/main_frame.htm" />
	<frame name = "side" src = "/html/side_frame.htm" />
</frameset>
						   
							


Iframe as <iframe> is also a tag used in HTML but it specifies an inline frame which means it is used to embed not only same domain but also other webpages within the current HTML document. It is like a Television, it displays a thing which is present somewhere else.


							<iframe id="ifr" name="demo" src="demo.html" height="200" width="300"></iframe>
							


Frame requires a frameset, but iframes donot requires framesets.

Placement of Frames are bit difficult comapared with iFrames

Adjusting the size and width of the Frame is difficult when compared with iFrame.

Frames cannot contains nested frames (frame inside frame) but iFrames can contain nested iFrames.

HTML5 doesnot support Frames, but supports iFrames.

Developers try to avoid using Iframes as these are external documents (webpages), so there is chance of Phishing.

Presence of Frame in Selenium Webdriver

It is important for tester to check whether an element is inside a iframe/frame or just on webpage. If element is inside a frame then we have to switch into frame to access the element. 1. Right click on the page (not on the element) which part you want to check .

2. On the right click options you can find This Frame Option, if this option is present then there is a iframe else there is no iframe frame-selenium-webdriver 3. Webpage without frame. noframe-selenium-webdriver

How to find iframe/frame in Selenium webdriver

We can find the iframe/frame using right click in manual testing, finding the iframe/frame in selenium is little tricky one.

Below are the ways to fnd the iframe/frame:

Using ID
Using Name
Using Element (widely used)
Using Index

Using ID and Name are looks similar in syntax as these two are overloaded methods, find the examples below.

Using ID :
We can find the frame using Id attribute present in the iframe/frame


							<iframe id="ifr" name="demo" src="demo.html" height="200" width="300"></iframe>
							
							# switchong to a rame which has id as 'ifr'
							driver.switch_to_frame("ifr")
							


Using Name :
We can find the frame using name attribute present in the iframe/frame


							<iframe id="ifr" name="demo" src="demo.html" height="200" width="300"></iframe>
							
							# switching to a frame which has name='demo'
							driver.switch_to_frame("demo")
							


Using Element : Most of the time there will be multiple iframe/frame and few of them may share same id and name, so in such scenarios we cannot use id or name for finding the frame. So find the iframe/frame uniquely we have to find it as a element, the way we follow for normal elements.

Here we can use locators ( except id, name, as we used already) like classname, xpath css. We cannot use link text and partial link text as these two are only applicable for anchor tag <a>.

We also should refrain using tagname locator as there are multiple frame so we may not get the unique element.

Lets consider the below iframes, and xpath for this iframe would be :
Xpath for 1st iFrame : //iframe[@src='demo.html']
Xpath for 2nd iFrame : //iframe[@class='second']


							<iframe id="ifr" name="demo" src="demo.html" height="200" width="300"></iframe>
							<iframe id="ifr" name="demo" class='second' src="width.html" height="200" width="300"></iframe>
							<iframe id="ifr" name="demo" src="width.html" height="200" width="300"></iframe>
							
							# switch to 1st frame
							driver.switch_to_frame("//iframe[@src='demo.html']")
							


Using Index : Selenium webdriver assigns index to every frame present in the page, using index is the least preffered way of find the frame as in future frame position may change when development introduce another frame in between


							<iframe id="ifr" name="demo" src="demo.html" height="200" width="300"></iframe>
							<iframe id="ifr" name="demo" class='second' src="width.html" height="200" width="300"></iframe>
							<iframe id="ifr" name="demo" src="width.html" height="200" width="300"></iframe>
							
							# switch to 1st frame
							driver.switch_to_frame(1)
							


Handle single iFrame in selenium webdriver

If we want to access any element inside a iframe in selenium webdriver, we must find and switch to that iframe and access the element. Selenium webdriver throws NoSuchElementFound Exception unless we switch to the iframe.

single-frame-example-selenium-webdriver

Scenario : Fetch the value from the Topic (page level) and write it to topic textbar present in iframe 1

Page Url : http://chercher.tech/practice/frames-example-selenium-webdriver
single-frame-source-selenium-webdriver

Steps to solve scenario : 1. Open browser and navigate to : http://chercher.tech/practice/frames-example-selenium-webdriver


								# set the geckodriver.exe property an open browser
								driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
								driver.implicitly_wait(30);
								# open webpage
								driver.get("http://chercher.tech/java/frames-example-selenium-webdriver.php");
								


2. Get the text from the Topic element and store it in a string.


								# store the text value 
								textValue = find_element_by_xpath("//label/span").text
								


3. Switch to the Frame1, frame have attribute id='frame1' and which is unique so we can use id way switching to the frame.


								# switch to frame1
								driver.switch_to_frame("frame1");
								


4. Find the Text bar in the frame1 and enter the stored text.


								# set the value of the textbar to the value stored
								driver.find_element_by_xpath("//input[@type='text']".send_keys(textValue);
								


Complete program for single frame handling


								import unittest
								from selenium import webdriver

								class Test(unittest.TestCase):

									def test_open_alerts(self):
										driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
										driver.implicitlyWait(30);
										# open webpage
										driver.get("http://chercher.tech/java/frames-example-selenium-webdriver");
										# store the text value 
										textValue = driver.find_element_by_xpath("//label/span").text
										# switch to frame1
										driver.switch_to_frame("frame1");
										# set the value of the textbar to the value stored
										driver.find_element_by_xpath("//input[@type='text']".send_keys(textValue);

								if __name__ == "__main__":
									unittest.main()
								

Nested iFrame in selenium webdriver

Sometimes we will have multiple and nested iframes in a webpage, if we have nested iframes we have to switch to iframe inside frame.

We can access only content of frame when we are inside a frame, we cannot access outside the frame or inside any other frame.

Scenario : Check the check box present in the iframe 3 , iframe 3 is present inside iframe 1.

Page Url : http://chercher.tech/practice/frames-example-selenium-webdriver
nested-frame-selenium-webdriver

Solution to the scenario : Ignoring routine steps (open browser, page, wait)
1. Find the iframe1 and store it as webelement.


							# find the frame1 and store it in webelement
							frame1 = driver.find_element_by_id("frame1"));
							


2. Switch to iframe 1 using switch_to_frame() command


							# switch to iframe1
							driver.switch_to_frame(frame1);
							


3. Find the iframe 3 and swicth to it.


							# find the frame 3
							frame3 = driver.find_element_by_xpath("//iframe[@id='frame3']");

							# switch to frame 3
							driver.switch_to_frame(frame3);
							


4. Find the Check box and click it if it is not already checked.


							# find the checkbox
							checkbox = driver.find_element_by_xpath("//input[@type='checkbox']");

							# if check box is not selected then click the checkbox
							if( not checkbox.is_selected()):
								checkbox.click();
							
							


Complete programe to handle nested text bar.


							class NestedFrame(unittest.TestCase):
								def test_frames(self):
									driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
									driver.implicitlyWait(30);
									# open webpage
									driver.get("http://chercher.tech/java/frames-example-selenium-webdriver.php");
									# find the frame1 and store it in webelement
									frame1 = driver.find_element_by_id("frame1");
									# switch to frame1
									driver.switch_to_frame(frame1);
									# find the frame 3
									frame3 = driver.find_element_by_xpath("//iframe[@id='frame3']");
									# switch to frame 3
									driver.switch_to_frame(frame3);
									# find the checkbox
									checkbox = driver.find_element_by_xpath("//input[@type='checkbox']");
									# if check box is not selected then click the checkbox
									if( not checkbox.is_selected()):
										checkbox.click();
									
								
							
							

Navigate to Parent Frame


Switch to Parent Frame : switch_to.parent_frame() method in selenium switches the control to outer position(one place) in web page, the outer position could be a frame or page level.

In simple terms, parentFrame() method exits the current frame.

After performing a particular task we have move out of the frame, otherwise we cannot access the elements outside the frame.

Selenium Webdriver provides driver.switch_to.parent_frame() method to move out of the current frame, once we move out of the frame we can access the elements outside that frame but we cannot access the elements inside that frame

Scenario :
1. Check the check box present in the iframe 3, iframe 3 is present inside iframe 1,
2. After checking the check box, move back to iframe 1 and enter "selenium" text in the topic textbar
3. Now move back to page level and compare the topic(header) text is not equal to "selenium webdriver"

Page Url : http://chercher.tech/practice/frames-example-selenium-webdriver
parent-frame-exampe-selenium-webdriver

Solution to Scenario : skipping few steps which were covered in previous scenario.
1. Switch to iframe 1 and switch to iframe 3, check the checkbox

2. Now we have to navigate back to frame 1 by using driver.switch_to.parent_frame() method


							# navigate to parent frame, which is iframe 1
							driver.switch_to.parent_frame();
							


3. Find the textbar and enter the "selenium" text" in it.


							# set the value of the textbar to the value stored
							driver.find_element_by_xpath("//input[@type='text']").send_keys("selenium");
							


4. Now we have to navigate back to page by using driver.switch_to.parent_frame() method


							# navigate to parent, which is page
							driver.switch_to.parent_frame();
							


5. Find the topic header element and fetch the text.


							# store the text value 
							textValue = driver.find_element_by_xpath("//label/span").text;
							


6. Compare the topic text with expected value "selenium webdriver"


							if(textValue == ("selenium webdriver"):
								print("Topic value is equal to 'selenium webdriver'");
							
							


Complete program to use parent frame method


							class ParentFrame(unittest.TestCase):
								def test_frames(self):
									driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
									driver.implicitlyWait(30);
									# open webpage
									driver.get("http://chercher.tech/java/frames-example-selenium-webdriver.php");
									//find the frame1 and store it in webelement
									frame1 = driver.find_element_by_id("frame1"));
									# switch to frame1
									driver.switch_to_frame(frame1);
									# find the frame 3
									frame3 = driver.find_element_by_xpath("//iframe[@id='frame3']"));
									# switch to frame 3
									driver.switch_to_frame(frame3);
									# find the checkbox
									checkbox = driver.find_element_by_xpath("//input[@type='checkbox']"));
									# if check box is not selected then click the checkbox
									if( not checkbox.is_selected()):
										checkbox.click();
									
									# navigate to parent frame, which is frame 1
									driver.switch_to.parent_frame();
									# set the value of the textbar to the value stored
									driver.find_element_by_xpath("//input[@type='text']").send_keys("selenium");
									# navigate to parent, which is page
									driver.switch_to.parent_frame();
									# store the text value 
									textValue = driver.find_element_by_xpath("//label/span").text;
									//verify the value matches or not
									if(textValue == ("selenium webdriver"):
										print("Topic value is equal to 'selenium webdriver'");
									
								
							
							

Default Content


Default Content : switch_to_default_content() method exits all the iframes and the places the selenium control at the page level where as parentFrame() method exits the current iframe.

Once we reach page level we cannot access any elements inside the iframe unless we switch to it.

frames-example-selenium-webdriver

Scenario : Check the check box(frame 3), and select the 'Avatar' option from the Animals dropdown(frame 2).

Page Url : http://chercher.tech/practice/frames-example-selenium-webdriver default-content-frames-selenium-webdriver

Solution to the scenario :
1. Swicth to frame 1 and switch to frame 3
2. Check the checkbox
3. Now exit from all the frames using switch_to_default_content()


										# navigate to page level
										driver.switch_to_default_content();
										


4. Switch to iframe 2


										//switch to frame2
										driver.switch_to_frame("frame2");
										


5. Find the Animals dropdown and store it in type variable.


										//find the dropdown
										dropdown = driver.find_element_by_tag_name("select"));
										


6. Create object for select class, and call select_by_visible_text() method from the Select Class object.


										//Create object for select class
										sel = new Select(dropdown);

										//select the 'avatar' option
										sel.select_by_visible_text("Avatar");
										


Complete program for default content in selenium


										class DefaultContent(unittest.TestCase):
											def test_frames(self):
												driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
												driver.implicitlyWait(30);
												# open webpage
												driver.get("http://chercher.tech/java/frames-example-selenium-webdriver.php");
												//find the frame1 and store it in webelement
												frame1 = driver.find_element_by_id("frame1");
												# switch to frame1
												driver.switch_to_frame(frame1);
												# find the frame 3
												frame3 = driver.find_element_by_xpath("//iframe[@id='frame3']");
												# switch to frame 3
												driver.switch_to_frame(frame3);
												# find the checkbox
												checkbox = driver.find_element_by_xpath("//input[@type='checkbox']");
												# if check box is not selected then click the checkbox
												if( not checkbox.is_selected()):
													checkbox.click();
												
												# navigate to page level
												driver.switch_to_default_content();
												//switch to frame2
												driver.switch_to_frame("frame2");
												//find the dropdown
												dropdown = driver.find_element_by_tag_name("select");
												//Create object for select class
												sel = new Select(dropdown);
												//select the 'avatar' option
												sel.select_by_visible_text("Avatar");
											
										
										

We can write the above program in switch to parent Frame way as well


										class PageLevelParent(unittest.TestCase):
											def test_frames(self):
												driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
												driver.implicitlyWait(30);
												# open webpage
												driver.get("http://chercher.tech/java/frames-example-selenium-webdriver.php");
												//find the frame1 and store it in webelement
												frame1 = driver.find_element_by_id("frame1");
												# switch to frame1
												driver.switch_to_frame(frame1);
												# find the frame 3
												frame3 = driver.find_element_by_xpath("//iframe[@id='frame3']");
												# switch to frame 3
												driver.switch_to_frame(frame3);
												# find the checkbox
												checkbox = driver.find_element_by_xpath("//input[@type='checkbox']");
												# if check box is not selected then click the checkbox
												if( not checkbox.is_selected()):
													checkbox.click();
												
												# navigate to parent frame, which is frame 1
												driver.switch_to.parent_frame();
												# set the value of the textbar to the value stored
												driver.find_element_by_xpath("//input[@type='text']").send_keys("selenium");
												# navigate to parent, which is page
												driver.switch_to.parent_frame();
												# store the text value 
												textValue = driver.find_element_by_xpath("//label/span").text;
												if(textValue == ("selenium webdriver"):
													print("Topic value is equal to 'selenium webdriver'");
												
												# swicth to frame2
												driver.switch_to_frame("frame2");
												# find the dropdown
												dropdown = driver.find_element_by_tag_name("select");
												# Create object for select class
												sel = new Select(dropdown);
												# select the 'avatar' option
												sel.select_by_visible_text("Avatar");
											
										

										

Possible Routes of iFrame Navigation

Below images expains the possible routes of the iFrame navigation. possible-routes-selenium-webdriver

Multiple Windows in Selenium Webdriver

There will be times when you will required to perform some testing, where the testing operations open a new browser/tab, testcase may required you to perform some tasks on the newly opened browser window/tab and return back to original window to perform the remaining tasks.

Even if the window/tab is currently on focus but still it is not an active window, so to perform some tasks you need to switch to new browser window/tab in selenium webdriver.

Commands will have effect on base window unless we switch our control to new window/tab.

Previously tab and Windows are two different items, as tabs does not had any GU iD. Now developers made tab and windows have GUIDs, so tabs and windows are treated as same in selenium webdriver

Situations when we are likely to deal with multiple windows:

Filling forms may require to select the date from a separately opened window
Clicking on some link/button can open another window
Handling Advertisement windows

Multiple Windows


multiple-windows-handling-selenium-webdriver Above image depicts multiple browser windows

1. Our Application is opened on Parent/Base window, total number of windows is one

2. When clicking on a link/button our application opens two new windows along with base window, now the total number of windows present is Three (base + child-1 + child-2)

3. Now move to Child-1 window and perform click on a button/link which open another one more window along with child-window, now the total number of windows is 4 (base + child-1 + child-2 + grand child-1)

4. We can perform operation on grand child -1 window and we can close all windows or specif windows.

If we perform above operation manually, we may not find difficulty, but handling above scenario is tricky in selenium webdriver

Get Window Handles in Selenium webdriver

Selenium webdriver provides few methods to handle the multiple windows, let's see what are the methods and their uses.

GU ID:
GU ID abbreviation of Globally Unique Identifier, Every OS generates GU ID for application to identify them uniquely. We will be using this GU ID to handle the multiple browsers, GU ID is numeric string value.


										8589934593
										


current_window_handle :
current_window_handle method in selenium webdriver returns the current(active) browser's GU ID. It return GU ID as string value.


										driver.current_window_handle;
										


current_window_handle :
getWindowHandles method in selenium webdriver returns GU ID of all the browsers present at the moment, which are openend by current driver. This method returns GU IDs as Set of String.


										driver.window_handles;
										


switch_to_window() : switchTo() method in selenium webdriver helps user to switch between windows, frames, elements, alerts. switch_to_window(GU ID) method switches the control from the current browser window to target browser window which has the speccified "GU ID".


										driver.switch_to_window(guid);
										

Handle simple Two Browser Windows / Tabs

Click the button to Open a new window ( google.com)

Please use firefox as browser to open the link in new window, if you use chrome the link may be opened in new tab rather than new window.

two-windows-example-selenium-webdriver Steps to Handle Two Windows :
1. Open chrome browser and Navigate to http://chercher.tech/python/switchto


										# open chrome browser			
										driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
										# set implicit time to 30 seconds
										driver.implicitlyWait(30);
										# navigate to the url
										driver.get("http://chercher.tech/python/switchto");
										


2. Get the GU ID of the current (parent) window using current_window_handle method present in the selenium webdriver and store the value in a String


										# get the Session id of the Parent
										parentGUID = driver.current_window_handle;
										


3. Click on the Open New Window button, application open new window with google page. Make the selenium webdriver to sleep for 5 seconds, otherwise it may not fnd the newly pened tab.


										# click the button to open new window
										driver.find_element_by_id("two-window").click();
										time.sleep(5000);
										


4. Get the GU IDs of the two windows (parent + google), using window_handles method present in the Selenium webdriver. Store the GU IDs in a Set Collection, this Set will have GU IDs of both parent and Child Browsers


										# get the All the session id of the browsers
										allGUID = driver.window_handles;
										


5. iterate the Set of GUID values, and if the value is parent value skip it if not switch to the new window


										# iterate the values in the set
										for guid in all allGUID:
											# one enter into if blobk if the GUID is not equal to parent window's GUID
											if(guid != parentGUID):
												# todo 
											
										
										


6. Switch to window using switch_to_window() method present in selenium webdriver, pass the GU ID of the child browser to this method.


										# switch to the guid
										driver.switch_to_window(guid);
												
										


7. Find the search bar in Google.com and search for "success"


										# search on the google page
										driver.find_element_by_name("q").send_keys("success");
										


Close the Google tab/Window and return to parent tab/browser window


										# close the browser
										driver.close();
										# switch back to the parent window
										driver.switch_to_window(parentGUID);
										

Complete code for switching window may look like below


										class TwoWindows(unittest.TestCase) :
											def test_browser_Window :
												# open chrome browser			
												driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
												# set implicit time to 30 seconds
												driver.implicitlyWait(30);
												# navigate to the url
												driver.get("http://chercher.tech/python/switchto");
												# get the Session id of the Parent
												parentGUID = driver.current_window_handle;
												# click the button to open new window
												driver.find_element_by_id("two-window").click();
												time.sleep(5000);
												# get the All the session id of the browsers
												allGUID = driver.window_handles;

												# pint the title of th epage
												print("Page title before Switching : "+ driver.getTitle());
												print("Total Windows : "+allGUID.size());
												# iterate the values in the set
												for guid in all allGUID:
													# one enter into if blobk if the GUID is not equal to parent window's GUID
													if(guid != parentGUID):
														# switch to the guid
														driver.switch_to_window(guid);
														# break the loop
														break;
													
												
												# search on the google page
												driver.find_element_by_name("q").send_keys("success");
												# print the title after switching
												print("Page title after Switching to goolge : "+ driver.getTitle());
												time.sleep(5000);
												# close the browser
												driver.close();
												# switch back to the parent window
												driver.switch_to_window(parentGUID);
												# print the title
												print("Page title after switching back to Parent: "+ driver.getTitle());
											
										
										
										

										


output-two-window-selenium-webdriver

More than Two Window handling

We have handled the two windows in above tutorial by comparing GUID but when we have more than two window we cannot use the same approach. To access the exact page we may need title of the page, based on the title of the page we can differentiate the browser windows in selenium.

Tip : We can use title, url, element reference while switching into new window to ensure that we are switching to the required window. I prefer Tile, url than element



Scenario : Click on the Open 3 New Windows button, it will open three more windows (bing, google, yahoo), now switch to bing and search for "gates". four-windows-example-selenium-webdriver Steps to Handle More than Two Windows :
1. Open firefox browser and Navigate to http://chercher.tech/java/handle-multiple-windows-tabs-selenium

2. Get the GU ID of the current (parent) window using current_window_handle method present in the selenium webdriver and store the value in a String

3. Click on the Open 3 New Window button, application open new window with google page. Make the selenium webdriver to sleep for 5 seconds, otherwise it may not fnd the newly pened tab.

4. Get the GU IDs of the two windows (parent + google + bing + yahoo), using window_handles method present in the Selenium webdriver. Store the GU IDs in a Set Collection, this Set will have GU IDs of both parent and Child Browsers

5. Now iterate through the Set,switch to first GUID in Set and check the page title contains the keyword "bing".

Complete program for switching multiple windows in selenium webdriver


										class MoreThanTwoWindows(unittest.TestCase) :
											def test_browser_Window :
												
													# open chrome browser			
													driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
													# set implicit time to 30 seconds
													driver.implicitlyWait(30);
													# navigate to the url
													driver.get("http://chercher.tech/python/switchto");
													# get the Session id of the Parent
													parentGUID = driver.current_window_handle;
													# click the button to open new window
													driver.find_element_by_id("three-window").click();
													time.sleep(5000);
													# get the All the session id of the browsers
													allGUID = driver.window_handles;
													# print number of windows
													print("Total Windows : "+allGUID.size());
													//iterate through windows
													for guid in all allGUID:
														driver.switch_to_window(guid);
														# check the title of the page to match with "bing"
														if("bing" in driver.title.lower()):
															driver.findElement(By.className("b_searchbox").send_keys("gates");
															time.sleep(3000);
															break;
														
													
													# close all the windows
													driver.quit();
											
										
										

How do developer make the link to open in New Window

Developer can make the link to open in new window using target keyword present in anchor tag <a>, when developer set this value to "_blank", the link will be opened in new windows when user clicks the link.


											# button is nested inside a link
											<a id='two-window' href='http://google.com' target='_blank'><input type='button' value="Open New Window"></a>
											# plain link
											<a id='two-window' href='http://google.com' target='_blank'>Click me</a>
										


If developer avoids to use target='_blank', browser opens such links in same window. It is recommended not to open the link in new window


										<a id='two-window' href='http://google.com'>Click me</a>
										

Force to open in new Window rather than Tab

There will be situatons where we have to open a link in new Window, but later browser donot support opening a url in new window as it is not recommended ( phishing is easy with with new windows ).

During such scenarios we can use action class to open the link in new window, by pressing Shift key and to click the link, it opens the link in new window in selenium webdriver.

Steps to open link in a new Window :
1. Open firefox browser and Navigate to http://chercher.tech/java/handle-multiple-windows-tabs-selenium


										# open chrome browser			
										driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
										# set implicit time to 30 seconds
										driver.implicitlyWait(30);
										


2. Find the above link using id force-new-window and store it in a variable of type


										# store the element
										ele = driver.find_element_by_id("force-new-window");
										


3. Create a object for Actions class


										# create object for Actions class
										act = ActionChains(driver);
										


4. Call key_down method from the Actions class object, and pass Keys.SHIFT as parameter

5. Call Click method from the Actions class object, pass stored web element as parameter to this method

6. Use build() method from Actions class object to bind the key_down and click methods, call the perform method to perform the operations.


										# press the shift key
										act.key_down(Keys.SHIFT).click(ele).build().perform();
										


Complete program for opening a link in new window in selenium webdriver.


										class OpenNewWindow(unittest.TestCase) :
											def test_browser_Window :
												# open chrome browser			
												driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
												# set implicit time to 30 seconds
												driver.implicitlyWait(30);
												# navigate to the url
												driver.get("http://chercher.tech/python/switchto");
												# get the Session id of the Parent
												parentGUID = driver.current_window_handle;
												# store the element
												ele = driver.find_element_by_id("force-new-window");
												# create object for Actions class
												act = ActionChains(driver);
												# press the shift key
												act.key_down(Keys.SHIFT).click(ele).build().perform();
											
										
										

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
You can also share knowledge by Adding a topic here


Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech