How to upload file in Selenium Webdriver

In this article we will learn how to upload file in Selenium Web driver. It is very famous interview question.

How to upload file in Selenium Web driver

We can upload the file in Selenium Web driver using multiple ways
  • sendKeys (Recommended
  • Robot Class
  • Auto IT ( third party tool)
  • Sikuli (third party tool)

Upload file in Selenium Web driver using sendKeys

This is the most common method to upload a file in Selenium web driver. This can only be applied when you see attribute type = "file". Then only it is possible to use sendKeys().

driver.findElement(By.xpath("//input[@id='file']")).sendKeys("C:\\Selenium_file.docx");

Upload file in Selenium using Robot Class

Once you click on browse, you see a window. You have to perform below operation in order to perform any action using Robot class
  • Copy the path
  • CTRL + V
  • Press enter Key
First we have to create an instance of Robot class.

Robot rb = new Robot();
rb.delay(2000);                      //delay the time by 2000 ms


StringSelection ss = new StringSelection("c:\\file_path\\file.txt");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);       //copies the file to clip board

rb.keyPress(KeyEvent.VK_CONTROL);        // press CTRL key on your keyboard
rb.keyPress(KeyEvent.VK_V);                        //presses V

rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);

rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);

//Press action is always followed by release action






Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD