使用Chrome浏览器中的Robot,上传无法在selenium中运行

时间:2015-04-09 13:52:09

标签: java selenium selenium-webdriver awtrobot

我正在使用Robot类来上传文件,但它无效。

文件资源管理器正在上传,但Robot类无效:

driver = new FirefoxDriver();
driver.get("http://www.toolsqa.com/automation-practice-form");
driver.manage().window().maximize();
driver.findElement(By.id("photo")).click;
Thread.sleep(2000);

StringSelection stringSelection = new StringSelection("C:\\Users\\Desktop\\Bug\\ui_1.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);  
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);

Robot如何使用Chrome浏览器正常工作。面对Firefox的问题。有没有解决方案?

2 个答案:

答案 0 :(得分:0)

您实际上可以避免使用Robot并仅使用硒来解决它。只需将密钥发送到文件输入,然后提交表单:

WebElement photo = driver.findElement(By.id("photo"));
photo.sendKeys("C:\\Users\\Desktop\\Bug\\ui_1.png");

// TODO: fill out other fields

// this would find the corresponding form and submit it
photo.submit();

答案 1 :(得分:0)

等待几秒钟才能进入。在代码中添加robot.delay(3000);,如下所示。这可能会解决问题。

    Robot robot = new Robot();

    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);

    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);

    robot.delay(3000);

    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);