Uploading a file through selenium but file input e

2019-08-01 01: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条回答
闹够了就滚
2楼-- · 2019-08-01 02:11

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.

查看更多
登录 后发表回答