[英]File Upload using Selenium HtmlUnitDriver-headless webdriver
我正在尝试将本地文件(C:\\ sample.txt)上传到我的服务器。 我尝试使用Chrome网络驱动程序来实现这一点,并且它的工作原理绝对不错。 但是在用HTMLUnitDriver实现相同功能的过程中,我无法从本地磁盘浏览文件项。 我也尝试了以下两种方法,
1)发送密钥:
WebElement inputFile = driver.findElement(By.id("file"));
System.out.println(driver.getCurrentUrl());
LocalFileDetector detector = new LocalFileDetector();
String path = "C:\\UploadSample1.txt";
File f = detector.getLocalFile(path);
inputFile.sendKeys(f.getAbsolutePath());
2)使用机器人:
WebElement browseFile = fluentWait(By.id("browseFile"), driver);
browseFile.click();
File file = new File("C:\\UploadSample1.txt");
driver.switchTo().activeElement();
StringSelection fileNameToWrite = new StringSelection(
file.getAbsolutePath());
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(fileNameToWrite, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
我需要浏览文件项,然后只有我才能将其保存到服务器。 因为仅发送文件路径将在服务器磁盘中搜索文件。 现在我真的被卡住了,无法继续前进。
非常感谢您的帮助。 谢谢!
如果您需要先浏览到文件,恕我直言,这是不可能的; 为此,您将需要AutoIT(不建议使用Robot类)。 因此,最好的选择是使用sendKeys发送文件路径。
formInput.setValueAttribute(formValue);
对我来说很好。
程式码片段:
Iterator<String> formValueIterator = formValues.keySet().iterator();
while(formValueIterator.hasNext()){
String formKey = formValueIterator.next();
String formValue = formValues.get(formKey);
HtmlInput formInput = form.getInputByName(formKey);
if (formInput != null)
if (formInput instanceof HtmlPasswordInput) {
((HtmlPasswordInput)formInput).setValueAttribute(formValue);
} else {
formInput.setValueAttribute(formValue);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.