There are situations where we need to automate tasks such as
- Click on Browse (file explorer pops up)
- Select required file from explorer window
- click on open or upload.
“File explorer dialog” and click on “Open” is not browser objects, these are basically windows objects and can not be located using selenium locators.
We have several ways to perform the operation, let’s discuss some of the simple but effective ways to do this task…
-
Using Robot class
public static void main(String[] args) throws AWTException, InterruptedException { FirefoxDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://the-internet.herokuapp.com/upload"); //Select the file path with extension as string StringSelection selectstring = new StringSelection("C:\test.txt"); // Copy to clipboard Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selectstring,null); Thread.sleep(3000); WebElement dataFile = driver.findElement(By.id("file-upload")); dataFile.click(); // Create Robot class object Robot robot = new Robot(); Thread.sleep(1000); // Press CTRL+V robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); // Release CTRL+V robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_V); Thread.sleep(1000); robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); }
-
Using selenium sendKeys and submit
FirefoxDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://the-internet.herokuapp.com/upload"); WebElement dataFile = driver.findElement(By.id("file-upload")); dataFile.sendKeys("c:\test.txt"); dataFile.submit();
-
Using Autoit setup
Refer our earlier post Autoit with selenium
Whatever the upload controls you have in your application, any one of the above method will definitely work, let me know if any of the above doesn’t work
My personal suggestion is to use 2nd and 3rd method, using Robot class some times doesn’t work.