Selenium文件上载对话框弹出窗口未关闭

时间:2015-01-23 18:51:49

标签: java swing selenium

我使用以下代码片段在Java中使用selenium进行文件上传。文件的路径已成功粘贴到对话框弹出窗口,但对话框窗口未关闭或您说“打开”'未按下对话框窗口上的按钮。我认为关注这个' open'按钮是以某种方式改变的。这将导致我的文件无法上传。请提出建议!

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;

public static void setClipboardData(String string) {
  StringSelection stringSelection = new StringSelection(string);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
 And that is what i do, just after opening the "open" window:
 setClipboardData("C:\\path to file\\example.jpg");
 //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);

1 个答案:

答案 0 :(得分:0)

您不需要使用Robot课程。如果您有文件上传按钮,并将其存储为WebElement,则可以执行此操作:

//element is a WebElement of the upload button e.g.
WebElement element = driver.findElement(By.id("upload_btn"))
element.sendKeys("C:\\pathToFile\\example.jpg");