In this post I will give an example of how to upload a csv file with Selenium script to a webpage. Below is the screenshot of webpage:
Code to automatically select a csv file and then click Submit button is given below. Go through the comments in the code.
package login; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import java.awt.event.KeyEvent; //import com.thoughtworks.selenium.webdriven.commands.KeyEvent; public class upload_csv_file_using_send_keys { public static void main(String[] args) throws InterruptedException, AWTException { String Url = "https://colored.lmscheckout.com/"; WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get(Url); // before we can upload a file we need to login to the site driver.findElement(By.id("UserUsername")).sendKeys("colored@mailinator.com"); driver.findElement(By.id("UserPassword")).sendKeys("Colored123!"); driver.findElement(By.id("btnLoginHeader")).click(); driver.findElement(By.xpath("//a[@href='/AdminUsers/newUserForm']")).click(); //now go to target page where we need to upload the csv file driver.findElement(By.xpath("//a[@href='/AdminUsers/index']")).click(); //set the path of the csv file where it is located on local machine driver.findElement(By.xpaStringSelection("C:\\Users\\Webners\\Downloads\\colored_Namisha_sample_users_1470639510.csv"); StringSelection ss = new Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); Robot robot = new Robot(); //using keyboard keystrokes below we can select the file in the windows prompt and close the prompt robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); //On clicking submit button file will get uploaded driver.findElement(By.xpath("//input[@class=('btn btn-success btn-block')]")).click(); } }
Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com