Java 我可以使用selenium上传文件吗
我尝试使用selenium和java自动化一个网站。 但在网站中有一个字段用于从系统上载pdf文件。 如何在selenium中上载文件??Java 我可以使用selenium上传文件吗,java,selenium,file-upload,ui-automation,Java,Selenium,File Upload,Ui Automation,我尝试使用selenium和java自动化一个网站。 但在网站中有一个字段用于从系统上载pdf文件。 如何在selenium中上载文件?? 这里我附上该字段的屏幕截图请查看下面的代码,不要通过移动光标或按任何键来更改浏览器的焦点 public void navigateToWebSiteAndUploadFile() throws UnsupportedFlavorException, IOException, InterruptedException, AWTException {
这里我附上该字段的屏幕截图请查看下面的代码,不要通过移动光标或按任何键来更改浏览器的焦点
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启用
输入
字段,并使用它上载文件。您必须提供选择文件
按钮定位器作为webelement
和文件路径
,文件存在于您的系统中
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()
可以用您使用driver
实例的方式替换。我将它与getDriver()
函数一起使用
希望对您有所帮助。这能回答您的问题吗?请共享“选择文件”按钮的HTML。抱歉,它不起作用