Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file in Selenium WebDriver with no 'input' element

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&nbsp;<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.

like image 712
Thirunavukarasu Paramasivam Avatar asked Jul 17 '15 06:07

Thirunavukarasu Paramasivam


People also ask

Can we do file upload through Selenium?

We can upload files using Selenium Webdriver. This is achieved by the sendKeys method. We have to first identify the element which performs the file selection by mentioning the file path [to be uploaded].


1 Answers

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);
like image 140
Visko Avatar answered Sep 30 '22 09:09

Visko