【发布时间】:2020-04-21 18:08:47
【问题描述】:
我尝试使用 selenium 和 java 自动化网站。 但是在网站上有一个从系统上传pdf文件的字段。 如何在 selenium 中上传文件? 这里我附上那个字段的截图Screenshot
【问题讨论】:
-
请分享“选择文件”按钮的HTML。
标签: java selenium file-upload ui-automation
我尝试使用 selenium 和 java 自动化网站。 但是在网站上有一个从系统上传pdf文件的字段。 如何在 selenium 中上传文件? 这里我附上那个字段的截图Screenshot
【问题讨论】:
标签: java selenium file-upload ui-automation
请看下面的代码,不要通过移动光标或按任意键来改变浏览器的焦点。
public void navigateToWebSiteAndUploadFile() throws UnsupportedFlavorException, IOException, InterruptedException, AWTException {
// Create a file object
File f = new File("resources\\DemoUpload.txt");
// Get the absolute path of file f
String absoluteFilePath = f.getAbsolutePath();
//Copy the file path to clipboard
StringSelection autoCopiedFilePath = new StringSelection(absoluteFilePath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(autoCopiedFilePath, null);
//Navigate to the URL
driver.get("https://codepen.io/rcass/pen/MmYwEp");
driver.switchTo().frame("result"); //switching the frame by name
//Click on a button which opens the popup
driver.findElement(By.xpath("//input[@id='fileToUpload']")).click();
Thread.sleep(2000);
//This will paste the file path and name in the file explorer by pressing Ctrl +V combination.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// Pause should be used here to perform the action properly and release the Ctrl +V keys
Thread.sleep(2000);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(8000);
//press enter key after giving the file path.
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(5000);
}
【讨论】:
请试试这个。这个概念通过 Javascript 启用 input 字段并使用它来上传文件。您必须提供choose file 按钮定位器为webelement 和filePath,其中文件存在于您的系统中。
public void uploadFile(WebElement fileElement, String filePath) {
JavascriptExecutor executor = (JavascriptExecutor) getDriver();
String activateField = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible'; arguments[0].style.display='block';";
executor.executeScript(activateField, fileElement);
executor.executeScript(activateField, fileElement.findElement(By.tagName("input")));
fileElement.findElement(By.tagName("input")).sendKeys(filePath);
}
getDriver() 可以替换为您使用driverinstance 的方式。我将它与getDriver() 函数一起使用。
希望对你有帮助。
【讨论】: