当sendKeys不工作时,如何在Selenium中上传文件

问题描述 投票:0回答:2

HTML代码的类型为shadow DOM。

这是输入类型:

<input hidden type="file" id="fileInput" accept=".doc,.docx,.pdf,.jpg,.png">

console screenshot

javascript java selenium
2个回答
0
投票

您可以尝试通过执行JavaScript脚本,使用Selenium中的JavaScriptExecutor来隐藏此元素。我在我的项目中做了这种事情,因为在IE中SendKeys也没有用于隐藏输入。


0
投票

您需要使用JS使输入可见。完整步骤如下所述:

// Find file input element
WebElement input = driver.findElement(By.cssSelector("input[type='file']"));

// Make sure element is visible
((JavascriptExecutor) driver).executeScript("arguments[0].style.display = 'block';", input);

// Specify you local file path here
input.sendKeys("/path/to/file/on/machine/which/runs/tests");

如果是RemoteDriver,请不要忘记添加:

// Configure your client to upload local files to remote Selenium instance
    driver.setFileDetector(new LocalFileDetector());

注意:filepath应该是绝对的。你可以这样做:

String getFilePath(String filePath) {
    new File(filePath).absolutePath
}
© www.soinside.com 2019 - 2024. All rights reserved.