Sunday, November 4, 2018

Handling Frames in Selenium WebDriver | Selenium Tutorial

In this tutorial, I am going to cover how to handle Frames available on WebPages in Selenium WebDriver.


Topics To Be Covered -

  • What is Frame?
  • How to switch to Frame?
  • Different ways to identify Frame on web-pages.
  • How to navigate one Frame to another on the same web-pages?
  • How to get the total number of Frames on web-pages?

Frames in Selenium  








The HTML Frames are used to divide the web-page/browser window into different multiple sections where each section may or may not displays contents of the same web-page. It means each section can load the content of other websites also. 


How to inspect Frames on web-pages -



Here, I will take the website - 'https://seleniumhq.github.io/selenium/docs/api/java/' to explain the concept.



  • If you open the above URL, you will get above page. You can notice the entire page is divided into 3 sections. First two sections are at the left side and the third section at the right of the first two sections.
  • Right-click on the section highlighted in green on the below image and click on 'inspect' option.

  • Developer tools will be opened highlighting the property of the inspected element - 

  • Expand the developer tools upward and then scroll up until you get below result - 

  •  We can notice <frame> tag below the <head> tag. Inside the <frame> tag, we can get the 'Frame Name'. In our case, frame name is 'packageListFrame'.
Note - Similarly, we can get the other frames'name.

Handle Frames in Selenium Script - 

To handle frames, Selenium WebDriver provides a method - 
  • driver.switchToFrame(parameter);

Note -

We pass 'parameter' in the form of -
  1.  'Index of the Frame'
  2.  'Frame Name' and 
  3. ' Frame as WebElement'. 

Scenario 1 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Click on 'com.thoughworks.selenium' link.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we are trying to click on the link which is inside 'packageListFrame'. So if we run above program, we will get below compilation error -



NoSuchElementExpeption.



Scenario 2 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Switch to the above-identified Frame.
  • Click on 'com.thoughworks.selenium' link.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame("packageListFrame");//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we first switched to the frame then click on the link. So the program will run successfully.


Point to Note -

  • We can also switch to Frame using its index. Indexing of frame starts with '0', '1','2' and so on. So the index of the first frame is '0'. Therefore, the above program can be run as - 
 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame(0);//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we switched to the frame using its Index.


  • We can also switch to frame - first identifying the frame as a web-element and then switching to it. Here we will use x-path to locate the frame on the web-page. This is the most reliable method to switch to the frame. The above-described two methods use 'Frame Name' and 'Frame Index' to locate the Frame. But suppose, the name of the frame got changed or due to the insertion of the new frame on the web-page, the position of the frame got changed. But, this third method uses x-path to locate the frame.X-path directly locates the element wherever it is available on the web-page. It does not require any index or name to locate the element. That is why this method is more reliable.
Below image describes the x-path of the frame.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           WebElement frame_element = driver.findElement(By.xpath("//frame[@name='packageListFrame']"));//locating the frame element in order to switch to it.  
           driver.switchTo().frame(frame_element);//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we first located the frame on the webpage using x-path and then stored in the 'frame_element' variable. Since 'frame_element' is pointing to the frame, we used this as the parameter to switch to the frame in the above program.


How to switch from one frame to another -


To switch from one frame to another, Selenium WebDriver provided two methods -

  • driver.switchTo().defaultContent()
  • driver.switchTo().parentFrame()

This is possible to switch from one frame to another. However, We cannot directly switch from one frame to another. As we know a web-page/browser window is divided into multiple frames. Here web-page/browser window is the main window which contains those multiple frames. Frames are independent of each other. So if we are already switched to a frame then first we need to switch from this frame to the main window then we can switch to the other frames from there. The similar concept applies when a frame is itself divided into multiple frames.


Scenario 3 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Switch to the First frame(packageListFrame).
  • Click on 'com.thoughworks.selenium' link.
  • Switch to the Second Frame(packageFrame), highlighted in the below image in green color.



 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame("packageListFrame");//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
           driver.switchTo().frame("packageFrame");//Switching to the second frame  
      }  
 }  


Note - System will throw NoSuchFrameException while switching to the second frame as shown below.


Scenario 4 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Switch to the First frame(packageListFrame).
  • Click on 'com.thoughworks.selenium' link.
  • Switch to the main window.
  • Switch to the Second Frame(classFrame).
  • Click on 'org.openqa.selenium' link highlighted in green color.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame("packageListFrame");//Switching to the first frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the first target link.  
           driver.switchTo().parentFrame();//Switching to the main window.  
           driver.switchTo().frame("packageFrame");//Switching to the second frame  
           driver.findElement(By.xpath("//span[text()='Action']")).click();// clicking on the second target link.  
      }  
 }  


How to count total number frames available in web-page - 


 package com.sessions;  
 import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           List<WebElement> frame_count = driver.findElements(By.tagName("frame"));  
           System.out.println(frame_count.size());  
      }  
 }  


Note -

  •  Every frame in HTML structure starts with <frame> tag. So 'tagName' locator is used to locate frames in the web-page. 
  • findElements0 - returns List of WebElement.
  • frame_count - refers to all the frames available on the web-page.
  • size() - returns number of  elements referred by frame-count.

That all guys!!! 



Do comment in the comment box and share your views about the post. If you have any query, please comment on it. It will help me to reach to you and help you to resolve your query.

Friday, October 26, 2018

How to handle Alerts/Pop-ups in selenium WebDriver | Selenium WebDriver tutorial

In this tutorial, I am going to discuss how to handle alerts/pop-ups in selenium WebDriver scripts.

Topics to be covered - 
  • What is Alert?
  • Different types of Alert.
  • Alert Interface in Selenium WebDriver.
  • Methods of Alert Interface.
  • Practical Example.
  • Exception in Alert Interface.


Alert In Selenium





Alert is a small message box or pop-up that appears on the screen to display some notification/information to the users, asks permission form the users to perform some actions or asks some input from the users.


Types of Alerts -


 1. Simple Alert - This type of alert appears on the screen to give some notification/information to the users. It has the 'OK' button.




2. Prompt Alert - This type of alert appears on the screen to ask the user to input some values in the text field displayed on the alert box. It has 'OK' and 'CANCEL' buttons.





3. Confirmation Alert - This type of alert appears on the screen to get permission from the user to perform certain kind of actions It has 'OK' and 'CANCEL' buttons.





Alert Interface - 

To handle Alert pop-ups, Selenium provides an interface called Alert. To use it in the WebDriver script, we need to import one package

 import org.openqa.selenium.Alert;  

To handle Alert, WebDriver has provided one method -

  • driver.switchTo().alert() - This method switches to the alert available on the web-page. It returns a reference of the alert interface.


Methods provided by Alert Interface - 

  1.  void accept() - It clicks on 'OK' buttons.
  2. void dismiss() - It clicks on 'CANCEL' buttons.
  3. String getText() - It captures alert's message.
  4. void sendKeys() - It enters text value in the alert's text field.

Scenario
  1. Open rediff.com login page in chrome browser.
  2. Click on 'Login' button.
  3. Get the text of the alert box and verify it.
  4. If it verified then click on 'OK' button.


 package com.sessions;  
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class Selenium_Alert {  
      public static void main(String[] args) throws Exception {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           //launch rediff application.  
           driver.get("https://mail.rediff.com/cgi-bin/login.cgi");  
           //maximizing browser.  
           driver.manage().window().maximize();  
           //clicking on 'GO' button.  
           driver.findElement(By.name("proceed")).click();  
           //Creating Alert Interface  
           Alert alert = driver.switchTo().alert();  
           //Storing Expected Alert Message  
           String ExpectedAlertMessage = "Please enter a valid user name";  
           //Get text message of the alert box  
           String ActualAlertMessage = alert.getText();  
           //Putting execution of program in sleep for 5 secs.  
           Thread.sleep(5000);  
           //Comparing actual and expected. If matches click on 'OK' button.  
           if(ExpectedAlertMessage.equals(ActualAlertMessage))  
           {  
                alert.accept();  
           }  
      }  
 }  

Code Walk Through - 


1. Open rediff.com login page in chrome browser.

 //launch rediff application.  
 driver.get("https://mail.rediff.com/cgi-bin/login.cgi");  

2. Maximize the browser

 //maximizing browser.  
 driver.manage().window().maximize();  

3. Click on the 'GO' button.

 //clicking on 'GO' button.  
 driver.findElement(By.name("proceed")).click();  

Note - After clicking on the 'GO' button, an alert will be displayed. So, we need to switch to it as discussed above.

4. Create an Alert Interface reference and switch to the Alert.

 //Creating Alert Interface  
 Alert alert = driver.switchTo().alert();  

5. Store Expected Alert text message value in a string variable.

 //Storing Expected Alert Message  
 String ExpectedAlertMessage = "Please enter a valid user name";  

6. Get the Actual alert text message from the alert box and store it also in a string variable.

 //Get text message of the alert box  
 String ActualAlertMessage = alert.getText();  

7. Stop the execution of the program for some seconds.

 //Putting execution of program in sleep for 5 secs.  
 Thread.sleep(5000);  

Note - If you automate navigation to alert and performing any action on it, then these executions will happen so fast that you even won't be able to observe alert properly. So, it is necessary to halt execution of the program for some seconds in order to see the alert on screen.


8. Now, compare actual alert text message with the expected alert text message and if matches then only click on 'OK' button.

 //Comparing actual and expected. If matches click on 'OK' button.  
           if(ExpectedAlertMessage.equals(ActualAlertMessage))  
           {  
                alert.accept();  
           }  


Point To Note -

What if there is no alert and you wrote code for handling alert??

The system will throw NoAlertPresentException on the code line where you are trying to switch to alert.



That all guys!!! 

In my next tutorial, I am going to cover - How to handle frames in Selenium WebDriver



Do comment in the comment box and share your views about the post. If you have any query, please comment on it. It will help me to reach to you and help you to resolve your query.


Saturday, October 20, 2018

First WebDriver Script on IE browser : Selenium WebDriver tutorial

Hi guys, In this post, I am going to discuss how to execute selenium script in Internet Explorer browser.


 Pre-requisite - 


  • Make sure you have already installed Eclipse IDE.
  • Make sure you have already configured WebDriver-jar file with your java project.
  • Make sure you have downloaded the latest version of WebDriver-jar file. Otherwise, you will get a compiler error.
  • Make sure you have downloaded the driver for Chrome. I will show you below how to do it. 



Note - If you don't know how to configureWebDriver-jar with your java project, then refer the link - Configure webdriver -jar files with Java Project





How to run Selenium WebDriver script in IE browser






1. Open Eclipse.

2. Create one Java Project for example SeleniumTutorial.






3.  Right click on SeleniumTutorial and navigate as shown below - 






4. Create one package lets say com.selenium and click on Finish.
5. In the same way, right click on com.selenium and create one class for example SeleniumTutorial.







6.  Finally, your class will be created and will be shown as - 











How to download IEDriver?

  • Refer the link - Download IEDriver
  • Download the latest version zip file based on 32-bit or 64-bit supported by your PC and also based on your OS. 




  • Open the downloaded file and extract it. It will look like - 
  • Open the extracted folder and then copy the path.


Now we will write the script 
  1. Under the main body, write - 

 System.setProperty("webdriver.ie.driver", "F:\software\IEDriver");  

Note - If you notice you are getting an error. The reason is that Eclipse IDE does not understand single '\'. So, we have to provide '\\' and append the provided path with the file name with .exe extension as shown below -



System.setProperty() has two parameters - 
  • First parameter - We pass the name of the driver.
  • Second parameter - We pass the path of the extracted jar file. 
     
     2. Next, write below statement - 

 WebDriver driver = new InternetExplorerDriver();  

Here, 'driver' is the reference variable of WebDriver Interface. An object of InternetExplorerDriver class has been created. 'driver' reference is referring to the InternetExplorerDriver object. Since the reference to the object of InternetExplorerDriver is assigned to 'driver', now 'driver' has control over the InternetExplorer browser.


Note - You will get two errors. We have used an Interface and a Class and as discussed above, an Interface and Class implementations reside in a particular package, we need to import those respective packages. If you hover over where the errors are showing, you will be suggested with some actions to perform. what you need to do is to import below two packages -


 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  

     3. We will open the Google homepage.

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

Note:- get() - command is used to open a specific URL in the opened browser.

    4.  Now, we will close the browser.

 driver.close();  

Complete Code -


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 public class SeleniumIE {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.ie.driver", "F:\\software\\IEDriverServer_Win32\\IEDriverServer.exe");  
           WebDriver driver = new InternetExplorerDriver();  
           driver.get("https://www.google.com/");  
           driver.close();  
      }  
 }  

That all guys!!! 



Do comment in the comment box and share your views about the post. If you have any query, please comment on it. It will help me to reach to you and help you to resolve your query.