Friday, 29 March 2013

How to automate the Windows dialogs when you click the browse button on some web page using AutoIt.

I had this challenge of automating the window dialogs that gets prompted when we click on browse button on some web page. Googling for hours, i managed to collect information in bits and pieces. I did not find any example that showed me how to do it, end to end. As a result, i decided to do it myself.

To automate windows dialogs, i have used AutoIt - a powerful scripting language. Few lines from the AutoIt website:


AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying “runtimes” required!

Following are the steps, that i have taken to achieve this functionality:

Step 1: Downloaded AutoIt setup from here
            There are two important tools that comes as a part of the download. They are: SciTE Script
            Editor and AutoIt Window Info.

            SciTE is the script editor that i used to write the script &
            AutoIt Windows Info is the tool that i used to find the class types of the controls on the
            windows dialog (such as edit box & open button) shown below marked as red.

        
            

Step 2: Wrote the script using the SciTE Script Editor. Following is the script code. It is not very
            clean but does the job efficiently.

; Require variable declaration to increase script maintainability.
Opt("MustDeclareVars", 1);0=no, 1=require pre-declare

Main()

; Avoid global variables by implementing everything in functions
; and using the "Local" keyword.  In this script it doesn't matter (there
; is only one function), but this is a good practice to maintain to make
; your scripts less mysterious.
Func Main()
    ;Local Const $dialogTitle = "Select file(s) to upload by www.imageshack.us"
    Local Const $dialogTitle = $CmdLine[2]
    Local Const $timeout = 5
   ; Printer name should be a command line argument.
    ;Local Const $printerName = "Microsoft XPS Document Writer"
    Local $windowFound = WinWait($dialogTitle, "", $timeout)
   ; For some reason if the print dialog contains the list view (see below)
   ; and the window did not exist before starting WinWait, then the
   ; window returned seems to be something transient that we can't work
   ; with.  Therefore, try to find the window again.  Unclear why this
   ; would be necessary, but this seems peculiar to this type of print
   ; dialog.
  
    ;MsgBox(0, "", $dialogTitle)
    ;MsgBox(0, "", $CmdLine[1])
    ;MsgBox(0, "", $CmdLine[2])
   
  
    $windowFound = WinWait($dialogTitle, "", $timeout)
    Local $windowHandle

    If $windowFound Then
       ; Get the last window used by an AutoIt function, namely the window
       ; we were waiting for.
        $windowHandle = WinGetHandle("[LAST]")
        ;MsgBox(0, "", "Window found.")
       
        ;Now write code to set the filename editable drop down with the filepath which you want to upload.
        ;Local $outputFileName = "C:\Users\Davinder\Desktop\Personal\Davinder.png"
        WinActivate($windowHandle)
        ;Sleep($defaultSleepMs)
        ControlSetText($windowHandle, "", "[CLASS:Edit; INSTANCE:1]", $CmdLine[1])
        ControlClick($windowHandle, "", "[CLASS:Button; TEXT:&Open]")       
       
    Else
        ;ConsoleWrite("Could not find window " & $dialogTitle & @CRLF)
        MsgBox(0, "", "Could not find window.")
        Exit(1)
     EndIf
EndFunc   


Step 3: The script is then compiled to generate the exe file.
Step 4: Wrote a simple java source file and called the exe generated in step 3 from the java source
             file. The source code inside the java files is shown below:

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


public class AutoItAutomation
{
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        String browseButtonXpath = "//*[@id='SWFUpload_0']";
       
        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("http://www.imageshack.us/");

        try
        {
            WebElement element = driver.findElement(By.xpath(browseButtonXpath));
            element.click();
           
            /*
             * First arg  - is the path where you would keep the exe. Modify path as per your requirement.
             * Second arg - is the path of the file that you want to upload. Modify path as per your requirement.
             * Third arg  - is the title of the window / dialg that gets open up when you click on <browse> button. Modify it to the title that you get.
             */
            Process process = new ProcessBuilder("C:/Users/Davinder/Desktop/AutoIt Scripts/automate_windows_dialog.exe",
                               "C:\\Users\\Davinder\\Desktop\\Personal\\Davinder.png", "Select file(s) to upload by www.imageshack.us").start();           
        }
        catch(Exception e)
        {
            System.out.println("No such element found. Exiting smoothly.");
        }
        finally
        {
            //whether or not an exception is thrown, finally block will be executed
            //ensuring that all the resources are released.
           
            //driver.quit();
        }
    }//end of main method.
}

The browse button example that is used in this article for automation purposes is at : http://imageshack.us/

Comments are welcome.
Thanks :)

No comments:

Post a Comment