How to upload a file in Selenium WebDriver with no 'input' element
Solution 1
Check the DOM because somewhere there must be an <input type="file">
. The website's javascript will call the .click() of this element to pop up the file selector dialog and closing the dialog with a selection will provide the path. With Selenium the same can be achieved with the .sendkeys():
driver.findElement(By.xpath("//input[@type=\"file\"]")).sendkeys(localFilePath);
Solution 2
You are doing it almost correctly, except that sendKeys()
should be called on the input with type="file"
that is, most likely invisible in your case. If this is the case, make the element visible first:
Solution 3
This one works for me:
String CSVFile = "C:\\D\\Projects\\file.csv";
WebElement fileElement=this.driver.findElement(By.xpath("//[text()='fileElement']"));
this.wait.until(ExpectedConditions.elementToBeClickable(fileElement ));
fileElement .click();
StringSelection ss = new StringSelection(CSVFile);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//native key strokes for CTRL, V and ENTER keys
Robot robot = new Robot();
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);
Thirunavukarasu Paramasivam
I do manual and automation testing Test web and mobile application Write code in selenium to make the webbrowser to run parallel testcases Finding bugs and log it into assembla
Updated on June 04, 2022Comments
-
Thirunavukarasu Paramasivam almost 2 years
I have a HTML page with button named "Upload" and id:
btn-import-questions
. The element:<button class="btn btn-success btn-sm col-lg-11" id="btn-import-questions" data-ts-file-selector="questions-import-init"> Upload <i class="fa fa-upload"></i></button>
I tried a Selenium Java code like this:
driver.findElement(By.id("btn-import-questions")).sendkeys("C:/path/to/file.xlsx");
But since this is an upload button and not an input-type element, the above code is not working.