Thursday, 20 February 2014

How to upload file in selenium webdriver in Java?

Uploading file using selenium webdriver is very simple. All you have to do is – find the input element having type attribute’s value as file and then use sendKeys.

Below code will illustrate how we can upload a file using selenium webdriver in Java.

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


public class FileUpload {

 public static void main(String[] args) {
 
  System.setProperty("webdriver.chrome.driver", "F:\\chromedriver.exe");
  WebDriver driver =  new ChromeDriver();
        
  try{
  
   driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
   driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
   driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);  
     
   driver.get("http://www.xyz.com");
     
   WebElement uploadElement = driver.findElement(By.id("uploadfile"));

// enter the file path in file input field
uploadElement.sendKeys("C:\\abc.docx");

Thread.sleep(2000);
  }
 
  catch(Exception ex){
  
   System.out.println(ex.toString());
  
  }
  finally{
  
   driver.close();
   driver.quit();
  }
 }


}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors