我无法使用 sendKeys()
上传文件。这是我的代码
driver.findElement(By.xpath(Locators.browseFlagIconBtn)).sendKeys("D:\\Images\\icons.png");
我有一个用于文件上传的文件类型的输入标签
<input type="file" id="iconFlagFile" name="iconFile" onchange="setFlagIconFile()" value="" class=" file-input-opacity" style="position: absolute; z-index: 100; font-size: 200px; line-height: 200px; top: 0px; left: 0px; opacity: 0;">
但是,当我单击此输入字段所在表单的提交按钮时,我将被重定向到以下页面:
此问题的原因:
当我使用 sendKeys()
传递路径时,它会正确拾取需要上传的文件。但是,实际上传是在用户单击提交按钮时发生的。现在我不知道为什么它会搜索在 Chrome 目录中选择的文件,例如: "C:\Program Files (x86)\Google\Chrome\Application\53.0.2785.116"
显然它将无法找到该文件。
问题:如何解决这个问题?如果我需要提供更多信息,请告诉我。
最佳答案
请尝试以下 JavaScript 执行器代码
String filePath = "D:\\Images\\icons.png";
JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("document.getElementById('iconFlagFile').value='" + filePath + "';");
关于java - 使用 sendKeys() 在 Selenium 中上传文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39748411/