How to upload file in Selenium WebDriver using Robot class

Upload file using Robot class –

Suggested post to read –  How to upload file in Selenium WebDriver using sendKeys() method

In this article, we will see how can we upload file in Selenium WebDriver using robot class.

Upload file in Selenium WebDriver using ROBOT Class

This is another way using which we can upload file. Here we can do key press and key release using robot class.

This method is for handling the Windows File Upload dialog, which cannot be handled using Selenium. Please follow below steps:

1.   Click on the File Upload / Choose File button, so that the File Upload dialog is displayed.
        driver.findElement(By.xpath(“//*[@id=’uploadfile_0′]”)).click();

2. Copy your file’s absolute path to the clipboard
    StringSelection ss = new StringSelection(” C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx”);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

3. Paste the file’s absolute path into the File name field of the File Upload dialog box

    //native key strokes for CTRL, V and ENTER keys

    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

Refer below code –

package basicsOfSelenium;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

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


public class FileUploadInSelenium_UsingRobotClass {

 public static void main(String[] args) throws AWTException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://demo.guru99.com/selenium/upload/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //open upload window
     driver.findElement(By.xpath("//*[@id='uploadfile_0']")).click();

     //put path to your image in a clipboard
     StringSelection ss = new StringSelection("C://Users//Prakash//Desktop//Desktop//TOSCA tutorial.pptx");
     Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

     //imitate mouse events like ENTER, CTRL+C, CTRL+V
     Robot robot = new Robot();
     robot.delay(250);
     robot.keyPress(KeyEvent.VK_ENTER);
     robot.keyRelease(KeyEvent.VK_ENTER);
     robot.keyPress(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_V);
     robot.keyRelease(KeyEvent.VK_V);
     robot.keyRelease(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_ENTER);
     robot.delay(90);
     robot.keyRelease(KeyEvent.VK_ENTER);

  
 }

}

Refer below articles to learn more about Actions class in Selenium WebDriver –

Hope this helps !!

How to upload file in Selenium WebDriver using sendKeys() method

Let us talk about how to upload file in Selenium WebDriver. We can upload the file in selenium WebDriver using various methods. By using sendKeys() method is one of the simplest one.
Upload file in Selenium WebDriver using sendKeys
This is the simplest way to upload the file in selenium Webdriver. Here we will use sendKeys() method to send the absolute file path to be uploaded. But this can be achieved only when the type attribute for filepath textbox / browse button is “file”. Observe below screenshot for this.
As in above screenshot, since type = file, we can use sendKeys() method to send the file path & then click on upload / submit file button to complete upload process.
First make sure that the input element is visible
Don’t click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.
Instead you can use:
driver.findElement(By.xpath(“//*[@id=’uploadfile_0′]”)).sendKeys(“C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx”);
//*[@id=’uploadfile_0′] is the xpath of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.
Keep in mind that the upload file will work only If the element you send a file should be in the form    <input type=”file”>
Below is the sample example of how to upload file –

package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

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

public class FileUploadInSelenium1 {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://demo.guru99.com/selenium/upload/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //send the file path to be uploaded to the element, note - this will work only if attribute type = file
  driver.findElement(By.xpath("//*[@id='uploadfile_0']")).sendKeys("C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx");
  
  //click on accept term checkbox
  driver.findElement(By.xpath("//*[@id='terms']")).click();
  //click on submit button - to complete file upload
  driver.findElement(By.xpath("//*[@id='submitbutton']")).click();

  
 }

}
Well, this was all about upload file in Selenium webdriver by using sendKeys() method. There is another way to do it is by using AutoIT. Refer below link to know more about AutoIT

AutoIT Tutorials – Upload and download files in Selenium WebDriver

Hope this helps !!!

Handle datePicker in selenium using JavaScript

In this article, will talk about how to Handle datePicker in selenium using JavaScript.
Suggested post to read:
In old applications, the datepicker was in old style, that is, it was a kind of dropdowns, by using select class. But in new applications now, Datepicker are not Select element.
Datepicker are in fact table with set of rows and columns. To select a date, you just have to navigate to the cell where our desired date is present. Look at the below snapshot.
So, to handle this datePicker, we will write a java script, in which firstly we will enable the datebox (which is restricted by default to enter the value manually rather than selecting it from calendar pop-up). Then We will clear that filed & then enter the date by using sendKeys() method.
Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

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

public class HandleDatePcikerUsingJavaScript {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.redbus.in/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //This will select From date 
  WebElement elementFromDate = driver.findElement(By.id("onward_cal"));
  ((JavascriptExecutor)driver).executeScript ("document.getElementById('onward_cal').removeAttribute('readonly',0);"); // Enables the from date box
  elementFromDate.clear();
  elementFromDate.sendKeys("18-Aug-2017"); //Enter date in required format
  
  
 }

}

Hope this helps !!

How to use JavaScriptExecutor in selenium WebDriver?

In this article i will talk about how to use JavaScriptExecutor in Selenium WebDriver.

Suggested post to read:

 What is JavaScriptExecutor in selenium WebDriver?

Let us understand first what is JavaScriptExecutr. It is an interface which is used to execute JavaScript in selenium Webdriver code.

Selenium WebDriver uses pre-defined locators like id, class, Xpath, name, link etc. to locate the elements on webpage. So, in some cases, it becomes difficult to locate element or sometimes you may face consistency problem in locating element due to webpage code.

Many Situations occur in your project where code written with selenium – java (any language binding) does not work (at all or effectively).

There would be few tricky scenarios where just Webdriver object is not sufficient enough or optimum enough to handle with java for e.g. in few of my applications, the web page rendered is very long, and while doing operations with elements, I got errors. So, I used JavaScript in my script to handle the case. Some other cases where JavaScript comes handy is handling pop ups and alerts.

In another case, dropdown wasn’t working for me (it was not properly coded by using select class). It was selecting the elements with are currently visible, wasn’t searching in to the whole list. So, in this case, I need to keep scrolling down continuously & at the same time keep checking If the required option is available to select & is getting selected.

So, there are certain advantages involved when we use the two (java, JavaScript) judiciously in automation scripts. Both the languages are great in their own space.

What are the advantages of JavaScriptExecutr in Selenium?

1.      JavaScript is very efficient & accurate, as compare to the scripts written with Selenium-Java
2.     JavaScript executor allows you to run pure JavaScript code irrespective of the Selenium language binding (Java, C#, Python etc.) you are using.
3.     By using JavaScript, you can directly interact and /or alter elements on the page, more or less, like the page developer has done.
4.     JavaScript being a language which works very well with HTML offers innumerous workarounds/hacks on the page.
5.     JavaScript is recommended to use when Selenium – Java code tends to break for certain scenario, where JavaScript works perfectly.
6.     JavaScript is quite easy to pick up with the least amount of setup required. No special setup is required while using it with selenium
How to use JavaScriptExecutr (JavaScriptExecutr Syntax) –
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Where –
script – The JavaScript to execute
Arguments – The arguments to the script. (Optional)
Let us see few of the uses where we can use javaScripts in selenium WebDriver code.
       1.       To refresh browser
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
       2.       To get Webpage title
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript(“return document.title;”).toString();
        3.       To click on the button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
      where, element is the button webElement where you wanted to click.
         4.       To Scroll down the webpage
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.scrollBy(0,50)");
-> This is to scroll 50 pixels down.
If you want to scroll down till the end of webpage, then –
  js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        5.       To navigate to webpage –
JavascriptExecutr js = (JavascriptExecutr)driver;
js.executeScript("window.location = ‘URL-TO-BE-NAVIGATED’");

          6.       To enter text in textbox using JavaScript
           JavascriptExecutr js = (JavascriptExecutr)driver; 
           js.executeScript(“document.getElementById(‘lst-ib’).value = ‘Text to be searched’;”);
Example of JavaScriptExecutor –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

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

public class JavaScriptExample {

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

  //Navigate to google.com using javascript
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.location = 'https://www.google.co.in'");
 
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //Enter the text in textbox using javascript
  js.executeScript("document.getElementById('lst-ib').value = 'Text to be searched';");
  
  //Click on the button using javascript
  WebElement element  = driver.findElement(By.xpath("//*[@id='tsf']/div[2]/div[3]/center/input[1]"));
  js.executeScript("arguments[0].click();", element);

  //Get page Title using JavaScript
  String PageTitle =  js.executeScript("return document.title;").toString();
  System.out.println("Page title is: "+PageTitle);
  
  //To Refresh the browser using JavaScript
  js.executeScript("history.go(0)");
  
  //To Scroll Down the webpage 
    js.executeScript("window.scrollBy(0,50)");
    
    //to Scroll the webpage to bottom of page
    js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
 }

}

Hope this example helps little bit to understand how to use JavaScript in selenium – java code.

How to check if element / object is present on webpage?

In this article we will talk about, to check if particular element present on webpage or not.

In some cases, it is required to verify if element exist, click on the element if it exist.
Let us see how this can be achieved.
             1.       First Navigate to website.
             2.       We will use findElements here, so that we can check for all element with particular locator is present on webpage.
            3.       Get all the elements in a list.
            4.       If list is not empty, this means, element exist
            5.       If list is empty, this means, element is not present on webpage.
Look at the below example.
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

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

public class CheckIfElementPreesntOnWebPage {

 public static void main(String[] args) {

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

  if (driver.findElements(By.xpath("//a[@class='ico-login1']")).size() != 0 )
    {
   System.out.println("Element is present on WebPage");
  }
  else {
   System.out.println("Element is not present on webpage");
  }
 }

}

Refer below video –

Hope above example helps !!!

Extracting all links from web page / Bulk extraction of objects

In this article, we will talk about finding total number of objects (Links / Checkboxes / dropdown etc) present on the Web Page. We may need these things while counting total number of links present on web page, checking if all links are working properly etc.
Let us see how this can be done.
         a.       First Navigate to the webpage.
         b.       Get the list of all web-elements (which you need, could be either links, or checkboxes or dropdowns) using proper attribute type.
        c.       Get the count (total number of links) from the list.
        d.       Finally iterate over the list & get all desired objects.
Look at the below example.
Let us suppose, I want to find total number of links present on particular web page.

package basicsOfSelenium;

import java.util.List;
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;

public class ExtractAllLInks {

public static void main(String[] args) {

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

List<WebElement> allElements = driver.findElements(By.tagName("a"));
System.out.println("Total Number of Links present on this page is: "+allElements.size());

for (WebElement ele : allElements){
System.out.println("Link is: "+ ele.getText());
}

}

}

Now in case, if you want to find Number of checkboxes present on the web page, then use below –
List<WebElement> listOfCheckBoxes = driver.findElements(By.xpath("//input[@type='checkbox']")); 
Now in case, if you want to find Number of dropdowns present on the web page, then use below –

  List<WebElement> allDropdowns = driver.findElements(By.tagName("select"));
If you want to find total number of text boxes present on web page, then –
List<WebElement> allTextBoxes = driver.findElements(By.xpath("//input[@type='text'[@class='inputtext']"));
Hope this helps !!!!

Apache POI Introduction

What is Apache POI?

Apache POI is the java API for Microsoft documents like excel, word, PowerPoint, outlook, Visio, Publisher etc.
Some time, while automating web application, it is expected to read the input data from excel file, Sometime it is expected to generate reports in excel / word etc. So, in order to deal with this, one needs Apache POI. – which is a java API for Microsoft documents.
It is used to create new Microsoft document (like excel / word etc), to modify them, to access data from excel file / word file by using java programs.

POI have various components for various Microsoft documents. Below are the components of POI.
Components of Apache POI. – 
Excel (SS=HSSF+XSSF+SXSSF) –
HSSF is the POI Project’s pure Java implementation of the Excel ’97(-2007) file format. XSSF is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
PowerPoint (SL=HSLF+XSLF) –
HSLF is the POI Project’s pure Java implementation of the Powerpoint ’97(-2007) file format.
Word (WP=HWPF+XWPF) –
HWPF is the name of our port of the Microsoft Word 97(-2007) file format to pure Java. It also provides limited read only support for the older Word 6 and Word 95 file formats.
The partner to HWPF for the new Word 2007 .docx format is XWPF. Whilst HWPF and XWPF provide similar features, there is not a common interface across the two of them at this time.
Outlook (HSMF) –
HSMF is the POI Project’s pure Java implementation of the Outlook MSG format.
Visio (HDGF+XDGF) –
HDGF is the POI Project’s pure Java implementation of the Visio binary (VSD) file format. XDGF is the POI Project’s pure Java implementation of the Visio XML (VSDX) file format.
Publisher (HPBF) –
HPBF is the POI Project’s pure Java implementation of the Publisher file format.
Official WebSite of Apache POI is: https://poi.apache.org/
It is very common to use Excel file for Automation purpose. Here is how to get started with using excel file for automation purpose / data driven testing.
1. Download the latest release of the library here: Apache POI – Download Release Artifacts
2. Extract the zip file and add the appropriate JAR files to your project’s classpath:
– If you are reading and writing only Excel 2003 format, only the file poi-VERSION.jar is enough.
– If you are reading and writing Excel 2007 format, you have to include the following files:
  • poi-ooxml-VERSION.jar
  • poi-ooxml-schemas-VERSION.jar
  • xmlbeans-VERSION.jar
For Automation testing using Selenium WebDriver, we do not need all these things. What we need mostly is, how to read / write excel sheet (2003 / 2007 format). We may not be concerned about other uses of Apache POI.
So, let us study apache POI with below articles.

      1.       How to setup Apache POI in java – selenium Project.

           2.       How to read an excel 2003 (.xls) file using Apache POI

           3.       How to read an Excel 2007 (.xlsx) file using Apache POI

           4.       Writing Excel files using Apache POI

Hope this helps !!!!

Headless testing in selenium WebDriver using HtmlUnitDriver

What is headless testing?
Headless testing is nothing but the testing which is carried out with the help of headless browsers.

What is headless browser?
We can guess it form the name, Headless – do not have a head, this means, during testing, we cannot see browser running but it will run internally.
Headless browser is a browser without GUI. So, the browser accesses the webpages internally and perform actions on them, but user cannot see that.
Some if the examples of headless drivers include – 
HtmlUnit
Ghost
PhantomJS
ZombieJS
We will talk about HtmlUnitDriverhere.
HtmlUnitDriver is a faster an most light weight version of implementation of WebDriver.
By using HtmlUnitDriver, we can select the browser (Chrome / IE/ firefox) versions. This means we can emulate HtmlUnitDriver to other browsers.
HtmlUnitDriver is platform independent.
Advantages of headless testing – 
Headless browser is faster because no GUI appear during testing.
We can use this in a situation where you have to prepare test data, or you have to pass contents from one page to another page simply.
Let us look at the example, how can we use HtmlUnitDriver for headless testing?

package samplePackage;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.htmlunit.HtmlUnitDriver;


public class HtmlUnitDriverClass {

public static void main(String[] args) {

//initialize HtmlUnitDriver wit variable driver.

WebDriver driver = new HtmlUnitDriver();

driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");

System.out.println("Title of the page is: "+driver.getTitle());


}

}
Console Output: 
Title of the page is: About Software Testing . . .
When the above lines of code executes, no browser has been launched, but you can see, correct title of the page is been printed. what this mean is, browser has launched internally.

Testing different browsers on HtmlUnitDriver (headless testing)
We can test various browsers on HtmlUnitDriver for headless testing. Let us see  as below –
Select Mozilla Firefox  – 
                                HtmlUnitDriver driver = newHtmlUnitDriver(BrowserVersion.FIREFOX_38);
Select Chrome browser –
                                HtmlUnitDriver driver = newHtmlUnitDriver(BrowserVersion.CHROME);
Select IE browser – 
                                HtmlUnitDriver driver = newHtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_11);
Hope this helps !!!!

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 !!!!!