banner



How To Handle More Than 2 Windows In Selenium Webdriver

In this rapidly developing world of technology, i must e'er detect means to go along up with the time. Every bit the world is evolving towards software evolution, testing plays a vital role in making the process defect-free. Selenium Training is one such tool that helps in finding bugs and resolving them. This article on How to handle multiple windows in Selenium gives you an thought almost how y'all tin handle multiple windows while testing an application.

So, we'll showtime begin by taking a wait at the topics that nosotros'll be roofing in this article:

  • What is Selenium Webdriver?
  • How to run a test case in Selenium?
    • Pre-requisites
  • How to handle multiple windows?
    • Syntax
  • Demo

And so, before we get to know more most handling multiple windows in Selenium simultaneously, we'll meet what Selenium Webdriver is and learn how it functions.

Handling Multiple Windows in Selenium: What is Selenium Webdriver?

I bet nearly of the software testers out there must take worked with this amazing tool which makes their lives easier, and for those who don't know what is Selenium, I'll help you take your offset baby steps in exploring this tool.

Selenium logo - How to handle multiple windows in Selenium - Edureka

Selenium is an automation tool whose sole purpose is to test web applications adult past any system. Now, what's and so fascinating about this tool which makes it popular?

  • Selenium is an open source portable framework which helps in automating the testing of web applications.
  • Test scripts in Selenium can be written in whatever programming linguistic communication of your choice similar Java, Python, C# and many more.
  • Selenium has its ain gear up of commands called Selenese, which holds the series of commands.
  • Information technology can run beyond various web browsers like Chrome, Safari, Firefox, IE and many more than.
  • Selenium Webdriver interacts directly with the browser rather than interacting with the server.
  • It is fast and efficient.
  • Selenium is highly flexible when it comes to functional testing and regression testing.
  • Another interesting factor, Selenium makes utilise of chemical element locators which help in finding the element on a web folio. They are: grade, proper noun, XPath , ID, LinkText, DOM, Partial LinkText and CSS Selectors .
  • Information technology besides uses plugins like Maven , JUnit to test the applications more fast and effectively.

Now let's see how we can test an application using Selenium.

Treatment Multiple Windows in Selenium: How to Run a Test Case in Selenium?

To test any application in Selenium, we follow certain procedures which eventually helps in performing the desired tasks.

The basic pre-requisites to run a test-case are:

Pre-requisites to Run Selenium Exam-Case

  • The first matter we require is to choose the right programming linguistic communication to write the exam scripts. Equally Java is ane of the most elementary and like shooting fish in a barrel to sympathize language, we are going to add the JRE libraries to the project.
  • We require an IDE where we can run the exam scripts. There is NetBeans, Eclipse and many other IDEs but we adopt working on Eclipse IDE because it is highly effective while executing the Java projects.
  • Some Selenium plugins similar the Selenium standalone server, Selenium jar files, and Selenium IDE.
  • Browser drivers for unlike browsers like Chrome, IE, Firefox, etc.

Cheque out this commodity on how to set up Selenium to get an end to end guidance on the installation process.

So, in society to test an application, we need to know the basics of the programming language, which is Java in our instance. So get-go,

  • Initialize the webdriver and create an object of the same.
  • Instantiate the browser driver to the new ChromeDriver (in this instance, nosotros are working on ChromeDriver, y'all tin choose Firefox or IE) and specify the path in which the ChromeDriver exists followed by the extension of an executable file.
  • Get the URL of the particular web page which you lot desire to test
  • Find the element using one of the element locators in Selenium

Have a look at this video to get understand each and every nuance about testing an application.

How to Write & Run a Examination Case in Selenium | Selenium Tutorial | Selenium Preparation | Edureka

This video volition give you lot an introduction to an automated software testing tool – Selenium and help you understand how to write and run a test case.

And then, once we know how to run a test case in Selenium, we'll try altering the procedure past working across multiple windows simultaneously. To practise that nosotros'll run across a few functions which help usa doing it.

Handling Multiple Windows in Selenium: How to Handle Multiple Windows?

Now, what is a window handle role? How to handle multiple windows in Selenium while testing an application? Well, this will answer all your questions.

What is a window handle?

A window handle is a unique identifier that holds the address of all the windows. This is basically a arrow to a window, which returns the string value. This window handle part helps in getting the handles of all the windows. It is guaranteed that each browser volition have a unique window handle.

Syntax

  • go.windowhandle(): helps in getting the window handle of the electric current window
  • become.windowhandles(): helps in getting the handles of all the windows opened
  • set: helps to gear up the window handles which is in the form of a string.  fix<string> set= driver.get.windowhandles()
  • switch to: helps in switching between the windows
  • action: helps to perform sure actions on the windows.

These are a few new functions nosotros'll exist seeing in this demo. Apart from these, the rest of the functions assist in automating the process.

How to Handle Multiple Windows in Selenium Webdriver | Selenium Certification Training | Edureka

This video will help you lot understand how to handle multiple windows when you are testing an application using Selenium.

Handling Multiple Windows in Selenium: Demo

In this demo section, nosotros'll automate a few websites and cheque how to handle multiple windows.

We'll automate pages such equally,

  • ToolsQA website for testing the window handle function
  • We'll as well automate our official website edureka.co and perform some actions
  • Naukri.com which is i of the most pop online job portals

Now, we'll first starting time by testing the webpage ToolsQA

  • We volition first specify the browser driver on which nosotros are going to work and specify the path in which it is located using this command: Arrangement.setProperty("webdriver.chrome.commuter", "D:chromedriver.exe");
  • Instantiate the webdriver to the new chromedriver.
  • Get the URL of the web page that we desire to exam.
  • Inspect the chemical element and find information technology on the webpage using the element locators, in this instance, it is the ID.
  • After this, we need to open up multiple child windows. So, I'm going to do this using the for loop.
            package selenium;  import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver;  public class demo1 { public static void main(String[] args) throws InterruptedException { Organization.setProperty("webdriver.chrome.driver", "D:chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://toolsqa.com/automation-practice-switch-windows/"); WebElement clickElement = driver.findElement(Past.id("button1"));  for(int i = 0; i < 3; i++) { clickElement.click(); Thread.slumber(3000); }  } }        

Side by side footstep, nosotros'll add on a few more commands and notice the alter in the execution.

  • This is almost similar to the first project except that we need to impress the window handle of the parent and the child windows.
  • Get the handle of the parent window using the control: String parentWindowHandle = driver.getWindowHandle();
  • Print the window handle of the parent window.
  • Find the element on the web page using an ID which is an element locator.
  • Open multiple child windows.
  • Iterate through kid windows.
  • Pause the execution for a few seconds using the slumber command Thread.sleep(3000) where the time is specified in nanoseconds.
  • Get the handles of all the windows that are currently open using the command: Set<String> allWindowHandles = driver.getWindowHandles(); which returns the ready of handles.
  • Impress the handles of all the windows.
              package selenium;  import java.util.Set;  import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver;  public class demo2 { public static void primary(String[] args) throws InterruptedException {  Organization.setProperty("webdriver.chrome.driver", "D:chromedriver.exe"); WebDriver driver = new ChromeDriver(); commuter.get("http://toolsqa.com/automation-practise-switch-windows/"); String parentWindowHandle = driver.getWindowHandle(); System.out.println("Parent window'south handle -> " + parentWindowHandle); WebElement clickElement = commuter.findElement(Past.id("button1"));  for(int i = 0; i < 3; i++) { clickElement.click(); Thread.slumber(3000); }  Gear up<Cord> allWindowHandles = driver.getWindowHandles();  for(String handle : allWindowHandles) { Organisation.out.println("Window handle - > " + handle); }  }  }          

At present, nosotros'll customize the web page past adding a few more than commands to the above programme.

  • In this program, nosotros'll test the same web page ToolsQA and pass some other URL to the parent window.
  • Instantiate the browser driver to the new Chromedriver.
  • Get the window handle of the parent window and impress it.
  • Discover the chemical element on the folio using an ID which is an chemical element locator.
  • Employ for loop to iterate the number of child windows being created.
  • Become the handles of all the windows opened.
  • Print the window handle of the first window.
  • Use the SwitchTo control to switch to the desired window and also laissez passer the URL of the spider web page "google.com" to the current window.
              package selenium;  import java.util.Ready;  import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver;  public class demo4 {  public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://toolsqa.com/automation-exercise-switch-windows/"); Cord parentWindowHandle = driver.getWindowHandle(); System.out.println("Parent window'south handle -> " + parentWindowHandle); WebElement clickElement = driver.findElement(By.id("button1"));  for(int i = 0; i < 3; i++) { clickElement.click(); Thread.sleep(3000); }  Gear up<String> allWindowHandles = driver.getWindowHandles();  for(String handle : allWindowHandles) { System.out.println("Switching to window - > " + handle); Organization.out.println("Navigating to google.com"); driver.switchTo().window(handle); //Switch to the desired window first and and then execute commands using driver driver.become("http://google.com"); }  } }          

After this, nosotros'll run across how we can alter the child window without a change in the parent window.

  • The process is almost similar to the previous program but simply that after passing the URL, google.com, we volition be switching to the parent window and shut it.
  • After this, we will define the window handle of the last window and switch to this window and laissez passer the URL of the ToolsQA page. And so that this URL opens only in the terminal window and the other two child windows will however be showing google.com page.
              packet selenium;  import java.util.Prepare; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver;  public class demo5 { public static void primary(String[] args) throws InterruptedException {  Arrangement.setProperty("webdriver.chrome.driver", "D:chromedriver.exe"); WebDriver driver = new ChromeDriver(); commuter.go("http://toolsqa.com/automation-practice-switch-windows/"); String parentWindowHandle = driver.getWindowHandle(); System.out.println("Parent window's handle -> " + parentWindowHandle); WebElement clickElement = driver.findElement(By.id("button1"));  for(int i = 0; i < 3; i++) { clickElement.click(); Thread.sleep(3000); }  Set<String> allWindowHandles = driver.getWindowHandles(); String lastWindowHandle = ""; for(String handle : allWindowHandles) { System.out.println("Switching to window - > " + handle); System.out.println("Navigating to google.com"); driver.switchTo().window(handle); //Switch to the desired window first and and so execute commands using driver driver.get("http://google.com"); lastWindowHandle = handle; }  //Switch to the parent window driver.switchTo().window(parentWindowHandle); //close the parent window commuter.close(); //at this point there is no focused window, we accept to explicitly switch dorsum to some window. driver.switchTo().window(lastWindowHandle); driver.become("http://toolsqa.com"); } }          

At present, we'll test one of the top job portals Naukri.com

  • Set the arrangement property to Chromedriver and specify its path
  • Instantiate the webdriver to the new chromedriver
  • Get the URL of the web page and maximize the page
  • Get the window handle of the parent window
  • Go the window handles of all the windows
  • Next, we have alleged an object of type iterator to employ it for switching to the kid window and perform actions on information technology
  • We cheque if the principal window is equal to the child window or not, if(!mainweb.equals(kid)). If the main window is non equal to the child window, condition holds and we switch to the next kid window.
              package selenium; import org.testng.annotations.Test; import java.util.Iterator; import java.util.Set; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public course MultipleWindowsClass{ @Test public void testMultipleWindows() throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe"); // To open browser WebDriver driver = new ChromeDriver(); // To maximize browser driver.manage().window().maximize(); // To open Naukri website with multiple windows driver.become("http://www.naukri.com/"); // It will return the parent window name as a String String mainWindow=commuter.getWindowHandle(); // Information technology returns no. of windows opened by WebDriver and will return Ready of Strings Set<Cord> ready =driver.getWindowHandles(); // Using Iterator to iterate with in windows Iterator<String> itr= set.iterator(); while(itr.hasNext()){ Cord childWindow=itr.next(); // Compare whether the main windows is not equal to child window. If non equal, we will close. if(!mainWindow.equals(childWindow)){ driver.switchTo().window(childWindow); Organization.out.println(driver.switchTo().window(childWindow).getTitle()); driver.close(); } } // This is to switch to the master window driver.switchTo().window(mainWindow); } }          

Next, we'll perform some actions on our official website edureka.co

  • We'll initialize the webdriver to the new chromedriver.
  • Get the URL of the webpage.
  • We'll use the JavaScriptExecutor, it is an interface which provides a mechanism to execute Javascript through the Selenium WebDriver.
  • Get the window handle of the parent window.
  • Discover the element using XPath, which is an element locator and send keys to a particular location on the web page.
  • Scroll down through the page using the javascriptexecutor command: js.executeScript("window.scrollBy(X-axis, Y-axis)");
  • Become the handles of all the windows and print it.
  • Adjacent, we accept alleged an object of type iterator to utilise it for switching to the kid window and perform actions on information technology.
  • We bank check for this status if(!mainweb.equals(child)), if this condition holds, nosotros switch to the child window and also print the championship of it.
                parcel selenium;  import coffee.util.Iterator; import java.util.Set;  import org.openqa.selenium.Past; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;  public class demo3 {  public static void main(Cord[] args) throws InterruptedException { System.setProperty("webdriver.chrome.commuter","South:chromedriver.exe"); WebDriver driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; commuter.get("https://www.edureka.co/customs"); String mainweb = driver.getWindowHandle(); driver.findElement(By.xpath("//a[@grade='qa-logo-link edureka']")).sendKeys(Keys.SHIFT,Keys.ENTER); Thread.sleep(100); js.executeScript("window.scrollBy(0,400)"); Set <String> set = driver.getWindowHandles(); Organization.out.println(set); Iterator <String> itr = set.iterator(); while(itr.hasNext()) { js.executeScript("window.scrollBy(0,400)"); Cord child = itr.adjacent(); if(!mainweb.equals(child)) { driver.switchTo().window(child); System.out.println(driver.switchTo().window(child).getTitle()); // driver.close(); } } driver.switchTo().window(mainweb);  }  }            

Next, we'll automate the same webpage past customizing information technology.

  • The process is near like to the previous one but in this, we print the title of the current page.
  • Use the javascriptexecutor to whorl downwardly through a folio.
  • Observe the element using the chemical element locator XPath and transport keys( which is of the form string) to that particular element location.
  • Declare the web element Link to click on a item link on the page and in this case, nosotros want the link to open up in a new window.
  • Pause the execution for a few seconds after this.
  • Go the window handles of all the windows and impress them in a sequence.
  • Switch to the parent window and bank check if the championship matches. If it does, scroll downwards the folio using the javascriptexecutor. Find another chemical element on the spider web page using the element locator and specify the position of the new window.
  • Switch back to the parent window and scroll down through the page.
              package selenium;  import java.util.Gear up;  import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor;  import org.openqa.selenium.Keys;  import org.openqa.selenium.Point;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.WebElement;  import org.openqa.selenium.chrome.ChromeDriver;  import org.openqa.selenium.interactions.Actions;  //import org.openqa.selenium.support.ui.Select;  public class selenium { public static void main(String[] args) throws Exception  {  Arrangement.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");  WebDriver driver = new ChromeDriver();  driver.become("https://www.edureka.co/");  Cord title = commuter.getTitle(); Arrangement.out.println(championship);  //driver.go("http://www.google.co");  JavascriptExecutor js = (JavascriptExecutor) driver;  driver.findElement(Past.cssSelector("#search-inp")).sendKeys("Selenium Certification Form");  js.executeScript("window.scrollBy(0,40)");  driver.findElement(Past.xpath("//span[@grade='typeahead__button']")).click();  WebElement link = commuter.findElement(By.xpath("//li[@course='ga-allcourses']//a[@grade='giTrackElementHeader'][contains(text(),'Courses')]"));  Actions newwin = new Actions(driver);  newwin.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform();  //Thread.sleep(2000);  //js.executeScript("window.scrollBy(0,400)");  Thread.slumber(3000);  Set<String> windows = driver.getWindowHandles();  System.out.println(windows);  Organisation.out.println("a1");  for (String window : windows)  {  commuter.switchTo().window(window);  if (driver.getTitle().contains("Best Grooming & Certification Courses for Professionals | Edureka"))  {  Arrangement.out.println("a2");  js.executeScript("window.scrollBy(0,yard)");  System.out.println("b1");  driver.findElement(Past.xpath("//*[@id="allc_catlist"]/li[3]/a")).click();  driver.manage().window().setPosition(new Bespeak(-2000, 0));  }  }  Thread.sleep(3000);  Set<String> windows1 = commuter.getWindowHandles();  System.out.println(windows1);  System.out.println("a3");  for (String window : windows1)  {  commuter.switchTo().window(window);  System.out.println("a4");  js.executeScript("window.scrollBy(0,400)");  }  }  }            

At present let's check the output of the last programme.


First, we'll initialize the browser and get the URL of the web page nosotros want to exam and find the search box chemical element on the folio and ship keys to the searchbox and click the search icon.

First Window - How to handle multiple windows - Edureka
Subsequently this, we will open the class link in the new window using the activity command

Second Window - How to handle multiple windows in Selenium - Edureka
In one case we do this, we'll roll down through the kid window using the javascriptexecutor.

Scrolling through window - how to handle multiple windows in Selenium - Edureka
And later on this, print the title of the kickoff window and likewise the window handles of the 2 windows.
Output - how to handle multiple windows in Selenium - Edureka
At present with this, we come to an end to this "How to handle multiple windows in Selenium" blog. I Promise yous guys enjoyed this article and understood what is Selenium Webdriver and also understood how the window handle function helps in switching between the windows. At present that you lot have understood how to work on multiple windows simultaneously, cheque out the Selenium Certification Form past Edureka, a trusted online learning visitor with a network of more than 650,000 satisfied learners spread across the globe. This class is designed to innovate you to the complete Selenium features and its importance in testing software. Got a question for united states of america? Please mention it in the comments section of "How to handle multiple windows in Selenium" and we will get back to you.

Source: https://www.edureka.co/blog/handle-multiple-windows-in-selenium/

Posted by: moonalock1990.blogspot.com

0 Response to "How To Handle More Than 2 Windows In Selenium Webdriver"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel