【发布时间】:2018-06-05 09:06:57
【问题描述】:
我使用的是 mac 机器,我正在尝试自动化照片上传场景。
这是步骤: 1. 点击网页中的“添加照片”元素 2.会弹出系统对话框选择 3.一旦我在系统对话框中选择了一张照片(双击图像或单击并单击“打开”按钮)然后 4. 我会从网页上看到一个弹出窗口,显示所选照片的预览。 5.在那个弹出窗口中,我点击“上传”按钮。
我使用的机器人代码从我的桌面选择图像,但之后不执行任何操作。
有什么建议吗?或者有更好的方法吗?
public photo_upload_page clickOnAddphoto() throws Exception {
waitAndClickElement(addPhoto);
Thread.sleep(1000);
File file = new File("/Users/mohand/Desktop/Defect.jpg");
StringSelection stringSelection = new StringSelection(file.getAbsolutePath());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_TAB);
robot.delay(500);
//Open Goto window
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_G);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_G);
//Paste the clipboard value
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_V);
//Press Enter key to close the Goto window and Upload window
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(500);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(1000);
waitAndClickElement(buttonUploadPhoto);
return new photo_upload_page();
}
}
【问题讨论】:
-
"2. 会弹出系统对话框选择" 如您所知,该对话框属于操作系统(而不是浏览器)。这就是为什么任何脚本都无法访问该对话框的原因,否则可能会将代码直接走私到操作系统。
-
你需要避开对话。如果您有图像位置的输入字段,请使用 element.sendkeys("path to your image")。
标签: java selenium automation