问题描述
我有一个 HTML 页面,带有名为“上传”和 id: btn-import-questions
按钮。
元素:
<button class="btn btn-success btn-sm col-lg-11" id="btn-import-questions" data-ts-file-selector="questions-import-init"> Upload <i class="fa fa-upload"></i></button>
我尝试了这样的 Selenium Java 代码:
driver.findElement(By.id("btn-import-questions")).sendkeys("C:/path/to/file.xlsx");
但由于这是一个上传按钮而不是输入类型元素,所以上面的代码不起作用。
1楼
检查 DOM,因为某处必须有一个<input type="file">
。
网站的 javascript 将调用此元素的 .click() 以弹出文件选择器对话框,并通过选择关闭对话框将提供路径。
使用 Selenium 可以通过 .sendkeys() 实现相同的效果:
driver.findElement(By.xpath("//input[@type=\"file\"]")).sendkeys(localFilePath);
2楼
您几乎正确地执行了此操作,除了应在type="file"
的输入上调用sendKeys()
,也就是说,在您的情况下很可能是不可见的。
如果是这种情况,请先使元素可见:
3楼
这个对我有用:
String CSVFile = "C:\\D\\Projects\\file.csv";
WebElement fileElement=this.driver.findElement(By.xpath("//[text()='fileElement']"));
this.wait.until(ExpectedConditions.elementToBeClickable(fileElement ));
fileElement .click();
StringSelection ss = new StringSelection(CSVFile);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//native key strokes for CTRL, V and ENTER keys
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);
4楼
您可以使用 AutoIT 工具来执行此操作。 在 AutoIT .Au3 文件中使用以下代码进行上传。
sleep(1000)
If WinExists("[TITLE:Open]") Then
Local $hWnd = WinWaitActive ("[TITLE:Open]", "",15)
WinActivate($hWnd)
;WinWaitActive("Open", "", 10)
ControlFocus("Open","","Edit1")
ControlsetText("Open","","Edit1",$CmdLine[1])
ControlClick("Open","","Button1")
ElseIf WinExists("[TITLE:File Upload]") Then
Local $hWnd = WinWaitActive ("[TITLE:File Upload]", "",15)
WinActivate($hWnd)
;WinWaitActive("Open", "", 10)
ControlFocus("File Upload","","Edit1")
ControlsetText("File Upload","","Edit1",$CmdLine[1])
ControlClick("File Upload","","Button1")
Else
Local $hWnd = WinWaitActive ("[TITLE:Choose File to Upload]", "",15)
WinActivate($hWnd)
;WinWaitActive("Open", "", 10)
ControlFocus("Choose File to Upload","","Edit1")
ControlsetText("Choose File to Upload","","Edit1",$CmdLine[1])
ControlClick("Choose File to Upload","","Button1")
EndIf
然后在你的 C# 代码中使用下面的代码来调用它。
String sExe=(<EXE file path>+" "+<Upload file path>);
Runtime.getRuntime().exec(sExe);
Thread.sleep(5000);