Saturday, 1 November 2014

How to upload files in selenium web driver using AutoIT Script?

Some times you will have to handle the file upload window using selenium web driver.
Selenium does not provide any such way to handle the window pop ups.

You can use AutoIT script to automate this task. AutoIT is a scripting language for Microsoft windows applications. You will have to download and install AutoIT from this url Download AutoIT

Once downloaded, you can write below code in the script file and invoke that file code just when you need to handle the upload window. Semicolon(;) is used to mark the comments in AutoIT scripts.

;below line states Windows controller to wait for the window with title Open to display. Whatever is the name of window, you need to pass it here.

WinWaitActive("Open")

;below line will enter the file location to be uploaded.
Send("C:\Users\sagar\Documents\onion_fennel_bisque.jpg")

;finally we need to click on Ok or press enter to start the upload process.
Send("{ENTER}")

Here is the complete example.

package seleniumtest;

//autoIT
//TestNG
//Grid

//import the required classes
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public  class AutoIT {
 
 public static void main(String[] args) {
  
     WebDriver driver =null;
     //set the driver path
     System.setProperty("webdriver.chrome.driver",
 "F:\\selenium\\csharp\\chromedriver.exe");
     
     System.setProperty("webdriver.ie.driver", 
"F:\\selenium\\IEDriverServer_Win32_2.43.0\\IEDriverServer.exe");
     
     Date dNow = new Date( );
     
  
     //create new driver instance
    driver = new ChromeDriver();
  
     driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
   
     
      try{
       
       
       driver.get("https://www.pdftoword.com/");
       driver.findElement(By.id("file-uploader")).click();

                        //please note that below line calls the AutoIT
 script which will handle the file upload dialog in google chrome browser. 
Also note that we need to provide the path of exe file which
is created after we compile and build the AutoIT script.
Runtime.getRuntime().exec("F:\\selenium\\handlefile1.exe"); //wait for 2 seconds Thread.sleep(5000); }catch(Exception e){ //print exception if any System.out.println(e.getMessage() ); e.printStackTrace(); } finally{ //close the driver driver.close(); //quit the driver. driver.quit(); } } }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

About Me

My photo

Self-motivated software professional