How to click on <input type=file> across browsers using Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can click on a button with <input type= file> across browsers with Selenium webdriver. First of all we need to identify the element with the help of locators like xpath or css, then apply sendKeys() method where the path of the file to be uploaded is passed.

Let us see the html code of an element with input type as file. The corresponding representation of the element on the screen shall be.

For working with this element we need to first interact with the Browse button and also the path of the file to be uploaded should be valid.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class TypeFile{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[type='file']"));
      // file path passed with sendkeys()
      l.sendKeys("C:\\Users\\ghs6kor\\Pictures\\Desert.jpg");
      driver.quit();
   }
}

Output

raja
Published on 18-Sep-2020 10:14:39
Advertisements