How to take Screenshot of entire page in Selenium WebDriver?

Why to take screenshot is required in automation?

  • Screenshot helps us to understand the flow of application whether application is behaving correctly  or not.
  • It helps as while doing cross browser testing.
  •  Another use is, while doing headless testing, you will not see actual GUI screen, but it will run on backend (ex – by using HTMLUnitBrowser ), in that case, we can track failed tests.
  •    Screen shot is required in failure, so that we will get to know why the test case is failed.

To take screen shot in selenium, we have one predefined interface known as TakesScreenshot, we can not create object of an interface in java. So we need to typecast it to Webdriver object.
                          TakesScreenshot ts = (TakesScreenshot)driver;      
Explanation:    We can’t create object directly so typecast and then create.
                          File srcFile = ts.getScreenShotAs(OutPutType.FILE);   
Explanation:    Use the object created, then get screenshot as file & assign it to the File variable.
                        FileUtils.copyFile(srcFile, new File(“./ScreenShots/image1.png”);     
 Explanation:    Now you need to copy the srcFile, so use FileUtils class, then give source file & destination file. In destination file “.” (dot) refers to the current working directory.
Below is the sample piece of code which shows how to take a screenshot in selenium.

package basicsOfSelenium;

import java.io.File;

import java.io.IOException;

import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;



public class HowToGetScreenShotInSelenium {


public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();

driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();

//to take screenshot - observe below code

TakesScreenshot ts = (TakesScreenshot)driver; // We can’t create object of an interface directly so typecast and then create.
File srcFIle = ts.getScreenshotAs(OutputType.FILE); //Use the object created, then get screenshot as file & assign it to the File variable.

try {

FileUtils.copyFile(srcFIle, new File("./ScreenShots/test1.jpg"));

} catch (IOException e) {

e.printStackTrace();

}

driver.close();
}

}


 To know how to take screenshot of failed test case only, refer below post.

Refer – How to take screen shot of failed test case only?   <Link>

Hope this helps !!!!!

How to handle frame in selenium WebDriver?

In this article, i will talk about how to handle frame in selenium webdriver.

What is frame?

Frame is nothing but a container where few elements are grouped together. In short Frame is a HTML document within HTML document (Page). In HTML frames are also called as Iframe (Inline Frame). On HTML pages, iframes are mostly used to add content from another source (page), like advertisement.

How to Identify if frame is present on WebPage?

If you are unable to click on the element directly, please check if it is a frame. It is very simple to identify if it is a frame.
Right click on the frame. IF you see option like “This Frame” present after right click, then that is a frame & you need to handle it by switching it to that frame as explained further.

Below Image shows you how to identify frame.

On my blog : https://automationtalks.com/  My name card of LinkedIn appear as frame. refer below screenshot

If frame is there, means it should has either id or name. So that this frame id or frame name will be used to switch to this frame. Below image shows about frame id and frame name.
How to find total number of frames present on the webpage? 
Let us understand how can we find out how many frames are present on particular webpage.

As we saw earlier, the frame will have tagName “iFrame”. So we can use this tagname to find out number of frames present on the WebPage.

Get the number of frames in the list.

Example

List<WebElement> frameList=driver.findElements(By.tagName(“iframe”));
System.out.println(“Total number of frames present: ”+frameList.size());
Once we get to know about the frame, now question is how to handle this frame.

In order to deal with the elements present on the frame, first we need to switch to that respective frame. Let us see how this can be done

Scenario 1: If we know the number of frames present on the page-

If you know about number of frames present on the webpage, and you are sure about the frame number to which you wanted to switch, we can use index number (frame number) to switch to frame.

Note that, frames index number starts from 0. This means, for first frame, index would be 0.

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
		
		  try {
			  
			  driver.switchTo().frame(indexnumber); //here you can enter the index number
			  
			       }
			 catch (NoSuchFrameException e)
			      {            
			  
	System.out.println(e.getMessage());     
	
		
	}

Scenario 2: if you know the frame name.

If you know the frame name, How to handle frame, we can use –

                 WebDriver driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.manage().window().maximize();
		
		driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
		
		try {
			driver.switchTo().frame("frameName"); //enter the frame name here
			      } 
			 catch (NoSuchFrameException e)
			    {            
			    System.out.println(e.getMessage());     
			    }

Scenario 3: if you don’t know about number of frames and frame names.
If you are not sure about the frame id or frame name, then the only option you have is, using xpath.

WebDriver driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.manage().window().maximize();
		
		driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
	
		 try {
		 
		WebElement button=driver.findElement(By.xpath(""));  
		 
		driver.switchTo().frame(button);		 
		}
		catch (NoSuchFrameException e)
		     {          
		System.out.println(e.getMessage());     
		 
		     }
Note that, once you are done with operations on the frame, you need to switch back to you main page, using defaultContent menthod.

  driver.switchTo().defaultContent();
Hope, this makes you clear about how to handle frame !!!!

How to Verify ToolTip text using Selenium WebDriver?

What is ToolTip Text Message?

ToolTip message is the hint to GUI user. Below Screenshot shows ToolTip message.

There are two ways to read and verify tooltip message.

Verify ToolTip  text using Actions Class in Selenium WebDriver

1. Using Actions class

Whenever you focus on element and a tool-tip appears it is displayed inside a “div” which is made visible on mouse focus.

  1. Move to element using actions classActions action = new Actions(driver); action.moveToElement(‘element_to_be_focused’).build().perform();
  1. Now since tooltip displays some text, read that text and find out element from page source HTML where it is mentioned.
  2. Now simply write code to wait for visibility of element having tooltip text.
new WebDriverWait(driver, timeOutInSeconds).until(ExpectedConditions.visibilityOfElementLocated(‘element_locator’));
  1. Get text from tooltip element using getText()
 Below is sample code  –
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

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

public class VerifyToolTipMessage {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  driver.get("https://jqueryui.com/tooltip/");
  driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@class='demo-frame']")));
  
  new Actions(driver).moveToElement(driver.findElement(By.xpath("//input[@id='age']"))).build().perform();
  
  boolean isToolTipDisplayed = driver.findElement(By.xpath("//div[@class='ui-tooltip-content']")).isDisplayed();
  
  if (isToolTipDisplayed) {
  
   String tooltipText = driver.findElement(By.xpath("//div[@class='ui-tooltip-content']")).getText();
  System.out.println("Tooltip Text:- " + tooltipText);
  }
  driver.switchTo().defaultContent();
  
  driver.quit();
  
 }

}

2. Using “title” Attribute 

Whenever you will have tooltip then “title” attribute will be there

  package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

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

public class VerifyToolTipMessage1 {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
  String ToolTipText = driver.findElement(By.xpath(".//*[@id='mbtnav']/li[1]/a")).getAttribute("title");
  System.out.println("ToolTip message is: "+ToolTipText);
  driver.quit();
 }

}

Refer below links to learn more about Actions Class in Selenium WebDriver –

Hope this helps !!!

Difference between click and submit methods in Selenium webdriver?

In this article, i will talk about difference between click and submit method. Submit is for Forms and Click is for Buttons

If you submit using any element of Form, it will automatically find button with type ‘submit’ of form and click on it.

Submit can be done on any form item and click has to be done Button with type Submit

Both click() and submit() both are used to click Button in Web page.

Selenium WebDriver has one special method to submit any form and that method name Is submit(). submit() method works same as clicking on submit button.

.click() method :
You can use .click() method to click on any button. There is no restriction for click buttons.
That means element’s type = “button” or type = “submit”, .click() method will works for both.
If button is inside <form> tag or button is outside <form> tag, the click() method will work.

.submit() method :
we can use .submit() method for only submit form after click on button.
That means element’s type = “submit” and button should be inside <form> tag, then only submit() will work.
If element’s type = “button” means submit() will not work.
If button outside of the <form> tag means submit() will not work

For Example, Submit() will work if submit button should be inside <form> tag and element type=”submit” as below

<form>
<input id="submitbutton" name="submitbutton" type="submit" value="Next step" class=

"g-button g-button-submit">
</form>

But click() method will work for all  buttons in webpage with out any restrictions.

Hope this helps !!!

How to perform Drag Drop operation using selenium WebDriver?

Drag Drop operation can be implemented in Selenium WebDriver by using Actions class.

Using below 4 steps can explain how drag drop can be achieved using actions class.

perform Drag Drop using Actions Class using Selenium WebDriver
Step1: Create object of Actions class
Step2: Find out dragable Element.
Step3: Find out dropable Element.
Step4: Perform Drag and Drop using object of the actions class.
Syntax for drag and drop:
Actions action = new Actions(driver);
action.dragAndDrop(Sourcelocator, Destinationlocator).build().perform();
Observe below screen shot. We have one draggable element and one droppable element.
Below program illustrate drag and drop operation –
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class DragAndDrop {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();

  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();

  driver.navigate().to("http://jqueryui.com/resources/demos/droppable/default.html");

  WebElement draggableElement = driver.findElement(By.xpath("//*[@id='draggable']"));

  WebElement droppableElement = driver.findElement(By.xpath("//*[@id='droppable']"));

  Actions act = new Actions(driver);

  act.dragAndDrop(draggableElement, droppableElement).build().perform();

 }

}
Drag and Drop is done, refer below screenshot –
Hope this Helps!!!!

Difference between findElement and findElements in selenium WebDriver.

What is the difference between findElement() and findElements() in selenium WebDriver?

driver.findElement() and driver.findElements() both methods are used to find (locate) the WebElements. But as name suggest, they are different. Let us see the difference between them.
driver.findElement(): – 
 
            1.      Return single WebElement from the webpage.
         2.   If multiple WebElements with same location are present, then this returns first matching WebElement with specified locator.
            3.      If element is not found on the webpage, then it throws NoSuchElementFoundexception.
            4.      We can use WebElement methods on returned element again
Example – 

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://testing.webield.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.findElement(By.xpath("html/body/div[1]/div/div[2]/form/div[1]/div/input")).sendKeys("admin");

 driver.findElements(): –        
               
                  1.       Returns all (array of) matching elements with specified locator.
                  2.      findElements() is used to find the group of elements in to the list.
                  3.      This method returns List<WebElement>. That is the List of the WebElements.
                  4.      If no matching element is found, this method will return an empty List.
                 5.      As this method returns a list of WebElements, we have to get individual WebElement using for loop / iterator.
Example –

List<WebElement> l = element1.findElements(By.tagName("td")); 
System.out.println("Total elements present in table are: " +l.size());

for (int i = 0; i<l.size(); i++){
System.out.println("table contents: "+l.get(i).getText());

}

Hope this Helps!!!!

What is Synchronization in Selenium? How to Achieve Synchronization in Selenium?

 What is Synchronization ?
When two or more components work together, they should work in sync in order to achieve the desired result. If those components are not working in parallel or in sync, you may not get expected result. So, working of those components in sync or in parallel is termed as Synchronization.
In case of selenium test automation, there are two things who should work in parallel or in sync.
            1.       Application Under Test (AUT)
            2.       Testing tool (here, let us consider as Selenium)
Now, both of these two things (AUT & Selenium) have their own speed. Selenium Webdriver may be faster, but in some of the cases, application under test, takes some time for page load, or for web elements to be present on the webpage. In this case, Selenium Webdriver may not find those elements since the speed of Selenium Webdriver is faster as compare to Application (suppose). So here your tests will fail.
In order to overcome this situation, Application Under Test (website that you are testing) and your testing tool (Selenium in this case) should have same working speed. So, to match the speed of the application or in some case, to wait for specific conditions at some point of time, we use Synchronization, which helps to bring the AUT & Testing tool speed in sync. Now “Element Not Found” Error may not arise.
One of the way to implement wait is by calling thread.sleep() function however, it is not recommended because this is not very stable and unreliable. The time has to be specified in milliseconds.

There are 2 ways to Achieve Synchronization.
             1.       Implicit wait
             2.       Explicit wait
To understand about types of the wait, below links describe the Implicit and Explicit wait in more details –

Why not to use Thread.sleep(); toachieve synchronization in selenium?

What is Implicit wait? How to Achieve Implicit wait in Selenium?

What is Explicit wait? How to Achieve Explicit wait in Selenium?

What is Fluent wait? How to Achieve Fluent wait inSelenium?

Which is the best wait in selenium WebDriver?

 

Hope This Helps !!!!!

Why not to use Thread.sleep(); to achieve synchronization in selenium?

thread.sleep() in selenium
One of the way to achieve synchronization, implement wait is by calling Thread.sleep() function however, it is not recommended because this is not very stable and unreliable. The time has to be specified in milliseconds.
I think Thread.sleep() is considered as the worst case of explicit wait because, for Thread.sleep(), it has to wait for the full time specified as the argument of Thread.sleep(), before proceeding further.
it is not related to Implicit wait or Explicit wait…So we should not be confused due to resemblance in Sync method in Selenium and Thread.sleep.
The main disadvantage for Thread.sleep;statement is, there is a chance of unnecessary waiting time even though the application is ready.
We can achieve synchronization using Thread.Sleep, method of Java. However this is not recommended methodology. As it is same like asking selenium to stop executing for given X milliseconds so that our control is loaded and it is not guaranteed that within that hard coded X value, control is fully loaded and our test code can execute safely.
Ex: Thread. Sleep (20000);
Here the execution is halted for 20 Sec., even if the object we are looking exists at that instant, so it unnecessary waits of 20 sec.
or
Control exists after 10 sec. So here also selenium unnecessarily waits for more 10 sec.

Refer below posts to understand more about various types of synchronization.

Hope this helps.

What is Firefox profile, Need of Firefox profile?

What is Firefox Profile?
When we install Mozilla Firefox, Firefox creates a default profile, it contains a collection of bookmarks, extensions, passwords, history, preferred home page when you open browser, and another browser setting etc. …,
                We can customize this Firefox profile as per our automation testing need.  So, one can say like Firefox profile is nothing but different user is using Firefox.
Why do we need to Set Firefox Profile in Selenium WebDriver? 
Default Firefox contains a collection of bookmarks, browser settings, extensions, passwords, and history; in short, all of your personal settings.
When you trigger selenium with this browser you test become slow and unreliable. To make it lighter we generally create a custom profile which loads only required plugins and extensions with predefined settings.
In order to run all test successful, we need a browser which –
  • Loads easily (very lightweight profile
  • Proxy setting (if required)
  • SSL certifications handling (if required)
  • Company specific username and password to start browser (if required)
How to create Firefox Profile in Selenium WebDriver?
Let us assume that you wanted to have google as the startup page for Firefox. To do this we will need to update the “browser.startup.homepage” preference.
Follow below steps to add a website as your homepage:
1. Let’s first start by creating the FirefoxProfile object.
2. Now we will set the preference by using the below method.
3. To get the profile to be used, we need to pass it in to the driver. To do this, we need
to do the following:
FirefoxProfile ffprofile= new FirefoxProfile();

profile.setPreference("browser.startup.homepage","http://www.google.com");

WebDriver driver = new FirefoxDriver(ffprofile);

That’s it, this is all we can set Firefox profile.

Let us see some examples where we can use this Firefox Profile setting.

Below two articles explain the real time use of Firefox profile –

How to handle proxy setting using selenium Webdriver? 

How to Handle SSL Untrusted Connection in Selenium WebDriver ?

How to download Selenium ?

Download Selenium WebDriver Jars and configuring in eclipse.
In order to start with Automation testing using selenium WebDriver, we need below things –

1. Installed JDK or JRE on your machine.

           2. Installed Eclipse / NetBeans / or any other IDE
As we know, java is not a tool but it is a collection of jars which we need to use in eclipse or any other IDE. Here we will see how can this be achieved.

Step 1: Download Selenium WebDriver jar files.

Use below URL to download Selenium WebDriver jar files.
To Download Latest version, use this URL –   http://www.seleniumhq.org/download/
Once Selenium WebDriver jar has been downloaded, extract them to some folder. Now we will see how to configure these jar files in to our project.

Step 2: Create Java Project

Create Java project in eclipse so that we can configure selenium jars in to java project, which can be used for creating test cases.
Below steps explain how to create java project.
Click on File -> New -> Other
In select wizard, type Java, then select “Java project” from the list.
Give the desired project name & click on finish.
Now, Once the project is created, we need to create Package.
Right click on project that you have created.  Then go to New -> Package
Enter proper package name -> then click on Finish.
Now, once package is created, we need to create a class  where we can write our automation test cases.
Right click on Package, -> New -> class
Give some class name, then click on finish.
That’s it, now we have created a project along with package and class within it.

Step 3: Configure Selenium jar files in java project

Since now, we have created java project, package & class within it, its time to configure selenium jars within project. Below steps explains how this can be done.
Right click on the project -> Build Path -> Configure Build path
Go to Libraries, Click on Add External Jars -> Select the selenium jars (which you downloaded. Mentioned in step 1)
Click on Apply and OK
This is all done. To verify if your jars are added in to project, Check Referenced library in your project. It should contain all the jar files which you have added.
All set now, you are good to begin with your first test case using selenium
Hope this helps. Drop your comments.