Selenium Java File Uploads: sendKeys( ); Vs. Robot Class - Quick Guide

Опубликовано: 30 Август 2024
на канале: QA JUNCTION
41
13

In this video, you are going to learn how to upload the files using sendKeys(); and Robot Class in Selenium. Please find the code attached below. Thanks!!

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class FileUpload {

public static void main(String[] args) throws InterruptedException, AWTException {
// File Upload using sendKeys

System.setProperty("webdriver.chrome.driver", "C:\\Users\\Saikiran\\Downloads\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

//navigation to website
driver.get("https://ps.uci.edu/~franklin/doc/file_uplo...");
driver.findElement(By.xpath("//input[@name='userfile']")).sendKeys("C:\\Users\\Saikiran\\Downloads\\TestDoc.pdf");
}
}

Uploading the files using Robot Class
driver.get("https://ps.uci.edu/~franklin/doc/file_uplo...");
Robot rb = new Robot();
rb.delay(2000);
//ctrl+c - clipboard (copying path to clipboard)
StringSelection ss = new StringSelection("C:\\Users\\Saikiran\\Downloads\\TestDoc.pdf");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//ctrl+v - pasting the file path
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);

// Press Enter from Keyboard
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
}
}