我有一个带有名为&#34的按钮的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");
但由于这是一个上传按钮而不是输入类型元素,因此上述代码无效。
答案 0 :(得分:1)
你几乎正确地做到了,除了应该使用sendKeys()
在输入上调用 type="file"
,这很可能在你的情况下是不可见的。如果是这种情况,请首先使元素可见:
答案 1 :(得分:1)
检查DOM,因为某处必须有<input type="file">
。网站的javascript将调用此元素的.click()来弹出文件选择器对话框,并用选择关闭该对话框将提供路径。使用Selenium,可以通过.sendkeys()实现相同的目的
driver.findElement(By.xpath("//input[@type=\"file\"]")).sendkeys(localFilePath);
答案 2 :(得分:0)
您可以使用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);
答案 3 :(得分:0)
这个对我有用:
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);