Saturday, 22 August 2015

Scrolling web page with Selenium Webdriver using java

We can scroll the web page using javaScript Executor in the java code.We have taken the below example with three different scenarios of scrolling a webpage.
1. We may require to scroll to bottom of the page and then perform operations. For this scenario we have created a test 'scrollingToBottomofAPage'/
2. Some times, we may require to scroll to particular element and peform operations on that particular element. For this we need to pass the element on which we need to perform operation. For this scenario we have created a test 'scrollingToElementofAPage'/
3. We can also use the coordinates to scroll to particular position by passing the coordinates. For this scenario we have created a test 'scrollingByCoordinatesofAPage'/

package com.scroll.page;

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;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class PageScroll {
 WebDriver driver;
 String URL = "https://www.linkedin.com/";

 @BeforeClass
 public void setUp() {
  driver = new FirefoxDriver();
  driver.get(URL);
  driver.manage().window().maximize();
 }

 @Test(priority=1)
 public void scrollingToBottomofAPage() {
  driver.navigate().to(URL);
   ((JavascriptExecutor) driver)
         .executeScript("window.scrollTo(0, document.body.scrollHeight)");
 }

 @Test(priority=2)
 public void scrollingToElementofAPage() {
  driver.navigate().to(URL+"directory/companies?trk=hb_ft_companies_dir");
  WebElement element = driver.findElement(By.linkText("Import/Export"));
  ((JavascriptExecutor) driver).executeScript(
                "arguments[0].scrollIntoView();", element);
 }
 
 @Test(priority=3)
 public void scrollingByCoordinatesofAPage() {
  driver.navigate().to(URL+"job/?trk=hb_ft_jobs");
  ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
 }
 
 @AfterClass
 public void tearDown() {
  driver.quit();
 }
}
The more better way to do this is having a utils class and define reusable methods. We can call these methods from different classes/tests.
We need to pass the driver to the method.
 public static void scrollToBottom(WebDriver driver) {
        ((JavascriptExecutor) driver)
                .executeScript("window.scrollTo(0, document.body.scrollHeight)");
    }
In the same way, we may need to scroll to particular element and perform operations. To do this we need the below example reusable method. We need to pass the driver and element.
 public static void scrollTo(WebDriver driver, WebElement element) {
        ((JavascriptExecutor) driver).executeScript(
                "arguments[0].scrollIntoView();", element);
    }

File upload using Robots

We have discussed uploading a file using using Webdriver Sendkeys method and Using AutoIT Tool. Now here we will look into an other way of doing file upload using Robot class and StringSelection class in java.
Robot class is used to (generate native system input events) take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through with java code.
There are different methods which robot class uses. Here in the below example we have used 'keyPress' and 'keyRelease' methods.
keyPress - takes keyCode as Parameter and Presses here a given key.
keyrelease - takes keyCode as Parameterand Releases a given key
Both the above methods Throws - IllegalArgumentException, if keycode is not a valid key.
We have defined two methods in the below example along with the test which is used to upload a file.

package com.easy.upload;

import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class UploadFileRobot {

 String URL = "application URL";
 @Test
 public void testUpload() throws InterruptedException
 {
  WebDriver  driver = new FirefoxDriver();
  driver.get(URL);
  WebElement element = driver.findElement(By.name("uploadfile"));
  element.click();
  uploadFile("path to the file");
  Thread.sleep(2000);
 }
 
 /**
     * This method will set any parameter string to the system's clipboard.
     */
 public static void setClipboardData(String string) {
  //StringSelection is a class that can be used for copy and paste operations.
     StringSelection stringSelection = new StringSelection(string);
     Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
  }
 
 public static void uploadFile(String fileLocation) {
        try {
         //Setting clipboard with file location
            setClipboardData(fileLocation);
            //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);
        } catch (Exception exp) {
         exp.printStackTrace();
        }
    }
}

Download file using selenium webdriver

As we know we cannot simulate OS actions with Selenium. We use AutoIt tool to upload documents (when it is not possible to achive upload using sendKeys method). We have discussed uploading a file using using Webdriver Sendkeys method and Using AutoIT Tool in earlier tutorials.
To handle Download functionality with selenium, we need to do some settings to the browser using Firefox profile using preferences, so that it automatically download the files to the defined folder. Then we can write code to check if the folder is downloaded or not.
Below is the example program to download a file

package com.pack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.Test;

public class FileDownloadExample {
 
 public static String downloadPath = "D:\\seleniumdownloads";
 @Test
 public void testDownload() throws Exception {
  WebDriver driver = new FirefoxDriver(FirefoxDriverProfile()); 
  driver.manage().window().maximize();
     driver.get("http://spreadsheetpage.com/index.php/file/C35/P10/");
     driver.findElement(By.linkText("smilechart.xls")).click();
 }
 
 public static FirefoxProfile FirefoxDriverProfile() throws Exception {
  FirefoxProfile profile = new FirefoxProfile();
  profile.setPreference("browser.download.folderList", 2);
  profile.setPreference("browser.download.manager.showWhenStarting", false);
  profile.setPreference("browser.download.dir", downloadPath);
  profile.setPreference("browser.helperApps.neverAsk.openFile",
    "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
  profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
  profile.setPreference("browser.helperApps.alwaysAsk.force", false);
  profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
  profile.setPreference("browser.download.manager.focusWhenStarting", false);
  profile.setPreference("browser.download.manager.useWindow", false);
  profile.setPreference("browser.download.manager.showAlertOnComplete", false);
  profile.setPreference("browser.download.manager.closeWhenDone", false);
  return profile;
 }
}


We will explain you the preferences that we have set to Firefox browser.
setPreference("browser.download.folderList", 2);
Default Value: 1
The value of browser.download.folderList can be set to either 0, 1, or 2. When set to 0, Firefox will save all files downloaded via the browser on the user's desktop. When set to 1, these downloads are stored in the Downloads folder. When set to 2, the location specified for the most recent download is utilized again.

setPreference("browser.download.manager.showWhenStarting", false);
Default Value: true
The browser.download.manager.showWhenStarting Preference in Firefox's about:config interface allows the user to specify whether or not the Download Manager window is displayed when a file download is initiated.

browser. helperApps. alwaysAsk. force
True: Always ask what to do with an unknown MIME type, and disable option to remember what to open it with False (default): Opposite of above

browser. helperApps. neverAsk. saveToDisk
A comma-separated list of MIME types to save to disk without asking what to use to open the file. Default value is an empty string.

browser. helperApps. neverAsk. openFile
A comma-separated list of MIME types to open directly without asking for confirmation. Default value is an empty string.

browser. download. dir
The last directory used for saving a file from the "What should (browser) do with this file?" dialog.

browser.download.manager.alertOnEXEOpen
True (default): warn the user attempting to open an executable from the Download Manager
False: display no warning and allow executable to be run
Note: In Firefox, this can be changed by checking the "Don't ask me this again" box when you encounter the alert.

browser. download. manager. closeWhenDone
True: Close the Download Manager when all downloads are complete
False (default): Opposite of the above

browser. download. manager. focusWhenStarting
True: Set the Download Manager window as active when starting a download
False (default): Leave the window in the background when starting a download



http://seleniumeasy.com/selenium-tutorials/how-to-download-a-file-with-webdriver

Thursday, 30 July 2015

selenium-firefox-profile-for-saving-a-file - Download a file

http://stackoverflow.com/questions/12759256/selenium-firefox-profile-for-saving-a-file


    FirefoxProfile firefoxProfile = new FirefoxProfile();

    firefoxProfile.setPreference("browser.download.folderList",2);
    firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
    firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
    firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

    WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

    driver.navigate().to("http://www.myfile.com/hey.csv");
 
one more:
http://sqa.stackexchange.com/questions/2197/how-to-download-a-file-using-seleniums-webdriver
 

Monday, 27 July 2015

Logger in Java - Using this we can generate seperate log files for each test script

package data;

import java.io.File;
import java.io.PrintWriter;
import java.util.Date;

public class PrintWriterMethods {
   
    public static String filename="";
    public static PrintWriter pw= null;
    public static File file =null;
    public static String resultsFolder = "src/results/";
   
    public static boolean startLogger()
    {
        boolean flag = false;
        try{
            Date dt= new Date();
            String dt1 = dt.toString().replace("-", "_").replace(":", "_").replace(" ", "");
            System.out.println(dt1);
            filename = "summary"+ dt1 + ".txt";
            file = new File(resultsFolder + filename);
            pw = new PrintWriter(file);                       
            flag = true;
        }
        catch(Exception oExp){
            System.out.println(oExp.getMessage());
        }
        return flag;
    }
   
    public static String getFileName(){
        return filename;
    }
   
    public static void logFailer(String message){
        Date dt= new Date();
        pw.append(dt.toString() + "--FAILURE--" + message + "\r\n");
       
    }
    public static void closeLogFile(){
        Date dt= new Date();
        pw.append(dt.toString() + "--END OF THE SCRIPT--");
        pw.close();
    }
    public static void logSuccess(String message){
        Date dt= new Date();
        pw.append(dt.toString() + "--SUCCESS--" + message + "\r\n");
    }
    public static void logWarning(String message){
        Date dt= new Date();
        pw.append(dt.toString() + "--WARNING--" + message + "\r\n");
    }  
   
}










package data;
public class SubClassTest {

    public static void main(String[] args) {
        PrintWriterMethods.startLogger();
        PrintWriterMethods.logFailer("Print the step Failed..");
        PrintWriterMethods.logFailer("Print the step Failed2..");
        PrintWriterMethods.logSuccess("Print the step Failed3..");
        PrintWriterMethods.logFailer("Print the step Failed4..");
        PrintWriterMethods.logWarning("Print the step Failed5..");
        PrintWriterMethods.closeLogFile();
        System.out.println(PrintWriterMethods.getFileName());       
    }
}



Output: summaryMonJul2717_15_46IST2015.txt

Mon Jul 27 17:15:46 IST 2015--FAILURE--Print the step Failed..
Mon Jul 27 17:15:46 IST 2015--FAILURE--Print the step Failed2..
Mon Jul 27 17:15:46 IST 2015--SUCCESS--Print the step Failed3..
Mon Jul 27 17:15:46 IST 2015--FAILURE--Print the step Failed4..
Mon Jul 27 17:15:46 IST 2015--WARNING--Print the step Failed5..
Mon Jul 27 17:15:46 IST 2015--END OF THE SCRIPT--

Wednesday, 15 July 2015

Selenium and XPath

.//div[a[i[@class='fa fa-info-circle']]]//following-sibling::div[2]

To navigate to path, use: /.. or parent_tag name[and child xpath] 
eg:

1.       .//div[a[i[@class='fa fa-info-circle']]]                parent_tag[]: takes to parent element

2.        //[@class='fa fa-info-circle']/../..                      /..               : takes to parent element.


Consider below is the html source code:
div
      a
         i class="fa fa-info-circle"



----------------------
Contains text using xpath:           $x("//p[@class='help-block']/a[contains(text(),'here')]")
OR
for exact text matching using xpath: $x("//p[@class='help-block']/a[text()='here']")

3. Any tag having specific attribute:

      driver.findElement(By.xpath(".//*[@id='account']/a")).click();
 

Sunday, 5 July 2015

Java Details used in reporting results - Selenium

package com.utilities;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class reporters {
    public static String getTime(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss a");
        String formatDate = format.format(date);
        return formatDate;
    }   
   
    public static String getDate()
    {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("dd:MMM:YYYY");
        String formatDate = format.format(date);
        return formatDate;
    }
   
    public static String getTimeStamp()
    {
//        java.util.Date today = new java.util.Date();
//        return new java.sql.Timestamp(today.getTime()).toString();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("dd-MMM-YYYY HH:mm:ssss a");
        String formatDate = format.format(date);
        return formatDate;
    }
   
    public static String getDateTime()
    {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("dd:MMM:YYYY HH:mm:ss a");
        String formatDate = format.format(date);
        return formatDate;
    }
   
    public static long currentMilliSeconds()
    {
        return System.currentTimeMillis();
    }
   
    public static void sleep(int seconds)
    {
        try{
            Thread.sleep(seconds);
        }
        catch(Exception oExp)
        {
            System.out.println(oExp.getMessage());
        }
    }
   
    public static String getExecutionTime(long seconds1, long seconds2)
    {   
        long duration = seconds2-seconds1;
        return String.valueOf(TimeUnit.MILLISECONDS.toSeconds(duration));
    }
   
    @SuppressWarnings("finally")
    public static String getIPAddress(){
        InetAddress addr = null;
        try{
            addr = InetAddress.getLocalHost();
            String hostname = addr.getHostName();
            System.out.println("Hostname: "+hostname);
            System.out.println("IP Address: "+addr.getHostAddress());
//            System.out.println("Local Host: "+addr.getLocalHost());
        }
        catch(Exception oExp)
        {
            System.out.println(oExp.getMessage());
        }
        finally{
            return addr.getHostAddress();
        }
    }
   
   
    public static void main(String args[])
    {       
        System.out.println("getTime: "+reporters.getTime());
        System.out.println("getDate: "+reporters.getDate());
        System.out.println("getTimeStamp: "+reporters.getTimeStamp());
        System.out.println("getDateTime: "+reporters.getDateTime());
        long l1= reporters.currentMilliSeconds();
        reporters.sleep(3500);
        long l2 = reporters.currentMilliSeconds();
        System.out.println("getExecutionTime: "+reporters.getExecutionTime(l1, l2));
        System.out.println(reporters.getIPAddress());
    }
   
     
}


getTime: 22:31:43 PM
getDate: 05:Jul:2015
getTimeStamp: 05-Jul-2015 22:31:0043 PM
getDateTime: 05:Jul:2015 22:31:43 PM
getExecutionTime: 3
Hostname: Adi-PC
IP Address: xxx.xxx.x.x
xxx.xxx.x.x