Uploading a file through selenium but file input element is hidden

喜夏-厌秋 提交于 2019-12-11 06:33:22

问题


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!


回答1:


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 or width=0;
  • position outside of displayable coordinate (e.g. left=-1)

In your code you show height and width equal to 0, but only reset height. Try following JS:

String js = "arguments[0].style.height='1'; arguments[0].style.width='1'; "
            + "arguments[0].style.visibility='visible';";

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 to button wrapping input[@type='file'] element, setting display=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 execute sendKeys() method on it. The method has no return type and does not through exception in this case.



来源:https://stackoverflow.com/questions/15095601/uploading-a-file-through-selenium-but-file-input-element-is-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!