File Upload using Selenium WebDriver and Java Robot Class.

SeleniumAutomation TestingTesting Tools

We can upload a file with Java Robot class in Selenium webdriver. It can produce simulationsfor the Keyboard and Mouse Event. It is derived from the AWT package.

Syntax

Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

Example

Code Implementation

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.awt.*;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.JavascriptExecutor;
public class RobotUplFile{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      driver.get("http://my.monsterindia.com/create_account.html");
      // scroll to reach upload button
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript("scroll(0,500)");
      // file path passed as parameter to StringSelection
      StringSelection s = new StringSelection("C:\\Users\\ghs6kor\\Pictures\\test.txt");
      // Clipboard copy
      Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s,null);
      //identify element and click
      driver.findElement(By.xpath("//*[text()='Choose file']")).click();
      // Robot object creation
      Robot r = new Robot();
      //pressing enter
      r.keyPress(KeyEvent.VK_ENTER);
      //releasing enter
      r.keyRelease(KeyEvent.VK_ENTER);
      //pressing ctrl+v
      r.keyPress(KeyEvent.VK_CONTROL);
      r.keyPress(KeyEvent.VK_V);
      //releasing ctrl+v
      r.keyRelease(KeyEvent.VK_CONTROL);
      r.keyRelease(KeyEvent.VK_V);
      //pressing enter
      r.keyPress(KeyEvent.VK_ENTER);
      //releasing enter
      r.keyRelease(KeyEvent.VK_ENTER);
   }
}

Output

raja
Published on 28-Dec-2020 13:20:22
Advertisements