I am trying to upload a file using Selenium but my input file element is hidden.
My hidden HTML is:
<input id="yui_3_9_0pr3_1_1361897421363_2239" type="file" style="visibility:hidden; width:0px; height: 0px;" multiple="" accept="">
and the select file button HTML is:
<button id="yui_3_9_0pr3_1_1361897421363_2242" class="yui3-button" tabindex="0" aria-label="Select Files" role="button" type="button" style="width: 100%; height: 100%;">Select Files</button>
I tried the same thing using JavascriptExecutor
which you suggested but it still gives an exception ElementNotVisible: Element is not currently visible
.
This is my code:
WebElement fileInput = driver.findElement(By.xpath(//@input[@type='file']));
System.out.println("h14");
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
((JavascriptExecutor) driver).executeScript(js, fileInput);
System.out.println("h15");
LocalFileDetector detector = new LocalFileDetector();
String path = "//Users//pdua//Desktop//images.jpeg";
// File f = detector.getLocalFile(path);
//((RemoteWebElement)fileInput).setFileDetector(detector);
System.out.println("h16");
//fileInput.sendKeys(f.getAbsolutePath());
fileInput.sendKeys(path);
The XPath of the hidden input file element is //input[@type='file']
. Not sure if that is right or not!
Selenium will not interact with element if it is not visible and/or displayed. This could be caused by variety of the settings:
visibility=hidden
;display=none
;height=0
orwidth=0
;position outside of displayable coordinate (e.g. left=-1)In your code you show
height
andwidth
equal to 0, but only resetheight
. Try following JS:Additionally, inspect the
input[@type='file']
element in browser to check if there are any other styles or classes applied to it that can effect visibility. In my case, there was a class applied tobutton
wrappinginput[@type='file']
element, settingdisplay=none;
.NOTE: When changing the element visibility, the test is modifying the application under the test. It is an intrusive behaviour not recommended for the tests.
UPDATE: It appears element outside of the screen (e.g.
left=-1200
) is reported not displayed in Selenium, but it does not prevent Selenium to executesendKeys()
method on it. The method has no return type and does not through exception in this case.