我正在创建一个要求我上传文件的脚本,所以我写了类似的东西:
@FindBy(css = "div[title='Add an attachment'] button")
private WebElementFacade FILE_UPLOAD_BUTTON;
Path path = Paths.get(System.getProperty("user.dir"));
withTimeoutOf(20, TimeUnit.SECONDS).waitFor(ExpectedConditions.visibilityOf(FILE_UPLOAD_BUTTON));
FILE_UPLOAD_BUTTON.click();
filePath = Paths.get(path.toString(), "FolderName", "ActualFileName.pdf");
StringSelection fullPath = new StringSelection(filePath.toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(fullPath, fullPath);
Robot robot = new Robot();
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);
pause(2000);
它工作正常,但不是在无头镀铬。关于如何在Headless chrome上进行文件上传的任何想法? TIA。
编辑:添加了inquiry to serenity和wakaleo怀疑Robot类将在无头镀铬上工作,因为它与真实UI交互。我也试过他的建议使用标准的Selenium动作,如chord org.openqa.selenium.Keys;
和actions org.openqa.selenium.interactions.Actions;
,两者仍然不起作用
你可以使用AutoIt
和它的编辑器在selenium上传文件
1.您需要安装Autoit
及其脚本编辑器
我已共享该链接,您可以下载并使用它
https://www.autoitscript.com/site/autoit/downloads/
ControlFocus("Open","","Edit1")
ControlSetText("Open","","Edit1","E:\AutoIT\id.pdf")
ControlClick("Open","","Button1")
Runtime.getRuntime().exec(Globals.PROG_FILEUPLOAD);
执行此文件其中Global.PROG_FILEUPLOAD
是File Upload.exe的路径
PROG_FILEUPLOAD= "E:/AutoIT/File Upload.exe"
如果您有任何疑问,我也分享了您可以使用的参考链接
它不起作用,因为你正在使用Robot
类,这对于无头执行并不理想,因为无论如何浏览器都不可见。
确保您的上传元素可见。
之后,您使用以下内容上传:
driver.findElement(By.id("uploadElement")).sendKeys("path/to/file");
使用以下代码以无头模式上传文件:
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.get("http://nervgh.github.io/pages/angular-file-upload/examples/simple/");
driver.findElement(By.xpath("(//input[@uploader='uploader'])[2]")).sendKeys("C:\\NotBackedUp\\Python\\selenium-2.7.0\\py\\selenium\\selenium.py");
// Then click on some upload button
在sendKeys()方法中提供要上载的文件的完整路径。