Sunday, March 21, 2010

Selenium: Upload Files

Selenium despite of being a great tool can be very painful at times. It is when you are trying hard to automate some action and despite of putting all the steps correctly Selenium fails to do what you want. If the warrior within you do not want to give up easily, you will definitely end up draining hours of energy to figure out that one li`l bit. In the end you may triumph or forfeit. I have gone through such experiences a number of times and many a times all the hard work pays in the end. In the jubilation of figuring out the riddle, I almost always forget to document steps those would help me in case I stumble upon the same situation later in time. But this time I made sure that I document it and put it on the Internet so that I can also change to a giver from an all time taker from the Internet.

This time I was trying to automate a part of web page where the script was supposed to upload a file by clicking on a browse button, choose a local file and upload it. Very easy to do when done manually but not so easy through Selenium if you don't know what exactly needs to be done. First of all, clicking on the browse button and selecting a file using selenium doesn`t work. Instead Selenium RC has a function, type(), which is used to type text into text boxes or text fields. This function can be used to type in the full path of the file into the browse element. Example:

$sel->type($locator, $filename);

Here $locator can be the name or id/value pair or just id of the browse element. For more information on locators in Selenium please see this.

Once Selenium has picked up the mentioned file using type function, now its time click on upload button. If you are lucky you'll need not to do anything more and just use click function of Selenium and get going. But modifying browse button tends to misbehave. I noticed that once you have used type function to select a file, Selenium will loose focus and won't be able to execute click function on upload button successfully. The solution of this is to get focus of upload button using focus function from WWW::Selenium and then use click function. So the final sequence turns out to be as below:

$sel->type('browseid', '/home/dir/filename');
$sel->focus('uploadid');
$sel->click('click');

This worked for me very well, hope will be helpful to all of you :)

1 comment:

  1. I am facing sme problem. I was using $sel->type('browseid', '/home/dir/filename'); without using $sel->focus functions.


    After reading your blog, I used it in my code but still there is no luck.


    Try one :-
    $sel->type_ok("whitefile", "C:\\Automation\\SWG\\TestData\\Whitelist_IP.txt");
    $sel->focus('uploadfile');
    $sel->click_ok("uploadfile");

    Try Two:-
    $sel->focus('whitefile');
    $sel->type_ok("whitefile", "C:\\Automation\\SWG\\TestData\\Whitelist_IP.txt");
    $sel->focus('uploadfile');
    $sel->click_ok("uploadfile");

    no luck....

    ReplyDelete