我正在使用PhantomJSDriver / GhostDriver运行无头脚本,并尝试在编写电子邮件时在gmail上传文件。
工具:Selenium with PhantomJS / GhostDriver。
html代码如下:
Click the "Browse" button to select a file. Click "Done" when you're finished.</table><table width=100% cellpadding=2 cellspacing=0 border=0>
<tr><td align=right>1. </td><td>
<input name="file1" type=file size=42><tr><td align=right>2. </td><td>
<input name="file2" type=file size=42><tr><td align=right>3. </td><td>
<input name="file3" type=file size=42><tr><td align=right>4. </td><td>
<input name="file4" type=file size=42><tr>
到目前为止,我已经尝试了以下两种方法来上传文件,但它们都没有工作:
使用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');");