Selenium GhostDriver / PhantomJS:使用sendKeys()/ Javascript无法上传文件

我正在使用PhantomJSDriver / GhostDriver运行无头脚本,并尝试在编写电子邮件时上传gmail上的文件。

工具:Selenium与PhantomJS / GhostDriver。

html代码如下:

Click the "Browse" button to select a file. Click "Done" when you're finished.

到目前为止,我已经尝试了以下两种方法来上传文件,但它们都没有工作:

使用Javascript:

 wait.until(ExpectedConditions.presenceOfElementLocated(By.name("file1"))); WebElement btnChoseFile = driver.findElement(By.name("file1")); System.out.println(btnChoseFile.isEnabled()); File file = new File("attachments/Alan Morales.doc"); String script = "document.getElementsByName(\"file1\")[0].value='" + file.getAbsolutePath() + "';"; jsexec.executeScript(script); System.out.println("File attached....."); 

收到的例外情况:

 Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: {"errorMessage":"InvalidStateError: DOM Exception 11","request": {"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive", "Content-Length":"144","Content-Type":"application/json; charset=utf-8", "Host":"localhost:48470","User-Agent":"Apache-HttpClient/4.3.4 (java 1.5)"}, "httpVersion":"1.1","method":"POST","post":"{\"args\":[],\"script\": \"document.getElementsByName(\\\"file1\\\") [0].value='D:\\\\ECLIPSE\\\\WORKSPACE\\\\HeadlessTests\\\\.\\\\attachments\\\ \Alan Morales.doc';\"}","url":"/execute","urlParsed": {"anchor":"","query":"","file":"execute","directory":"/","path" :"/execute","relative":"/execute","port":"","host":"","password":"","user":"" ,"userInfo":"","authority":"", "protocol":"","source":"/execute","queryKey":{},"chunks": ["execute"]},"urlOriginal":"/session/3db602a0-d517-11e4-bb05- df9882695874/execute"}} 

使用sendKeys():

 wait.until(ExpectedConditions.presenceOfElementLocated(By.name("file1"))); WebElement btnChoseFile = driver.findElement(By.name("file1")); System.out.println(btnChoseFile.isEnabled()); File file = new File("attachments/Alan Morales.doc"); btnChoseFile.sendKeys(file.getAbsolutePath()); System.out.println("File attached....."); 

当我使用sendKeys()时,PhantomJS挂起。

问题 :有没有办法使用Selenium + PhantomJS上传文件? 谢谢。

编辑 :我也尝试过以下声明。 虽然,该语句不会给出任何错误,但它不会上传文件。

 (PhantomJSDriver) driver.executePhantomJS("var page = this; page.uploadFile('input[type=file]', 'path to file');"); 

    1.
    2.
    3.
    4.