Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click on <input type=file> across browsers using Selenium Webdriver?

I'm working on dealing with a file-chooser dialog using Selenium 2 - WebDriver. Believe it or not, my problem is NOT dealing with the OS-native file-chooser. That part I can handle!

The problem is getting Selenium to properly click on the "Choose File" button. Since the original source html is simply <input type='file'>, the browser determines how to render it as a field and a button. As a result, the placement and naming of the button changes depending on browser. I've got it working in Chrome, but only because Chrome places the button on the leftmost alignment and Selenium happens to click there by default.

Any ideas? It's not clear to me if an input of this type is truly navigable from within the DOM anyway...

like image 753
Stephen Gross Avatar asked Mar 15 '12 18:03

Stephen Gross


People also ask

How do you click input in Selenium?

We can click on a button with <input type= file> across browsers with Selenium webdriver. First of all we need to identify the element with the help of locators like xpath or css, then apply sendKeys() method where the path of the file to be uploaded is passed.

Which method works with multiple browsers?

Cross browser testing refers to testing a website in multiple browsers like IE, Chrome, Firefox to check its efficacy on each. Cross-browser compatibility is the ability of the website or web application to function across different browsers and operating systems.

How do I enter text and click enter in Selenium?

We can type Enter/Return key in Selenium. We shall use the sendKeys method and pass Keys. ENTER as an argument to the method.


2 Answers

The proper way to upload a file on any OS is to

  1. Find the <input type='file'> element. You need not to worry about different implementations and exact positioning. Just find the element for example by xpath //input[@type='file']
  2. sendKeys() or type() (or whatever method writes text into elements in your language) the path to file to that input element.

Sample Java code:

// find the input element WebElement elem = driver.findElement(By.xpath("//input[@type='file']")); // 'type' the file location to it as it were a usual <input type='text' /> element elem.sendKeys("C://path/To/File.jpg"); 

This works on every OS and browser in WebDriver.

like image 184
Petr Janeček Avatar answered Sep 18 '22 07:09

Petr Janeček


Have exactly the same situation with element <input type='file'>. In my case it is created using ExtJS.

I don't know whether you have solved this question or not but let me provide my solution.

JavascriptExecutor executor = (JavascriptExecutor)getDriver(); executor.executeScript("arguments[0].click();", element); 

Neither sendKeys() or type() nor using ActionBuilder was helpful for me. The only JavascriptExecutor works like a charm.

like image 37
olyv Avatar answered Sep 18 '22 07:09

olyv