有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在SeleniumWebDriverJava中从文件夹上载图像

我正在使用selenium自动化移动网站。 在我的测试用例中,我需要上传图像。点击显示文件上传弹出窗口时,有一个id为addimage的摄像头图像。检查此流的图像

enter image description here

此文件的HTML代码:

<div class="clearfix">
    <ul id="imageList"> </ul>
   <div id="uploadimginput">
       <a id="addimage" class="sprite camera"> </a>
   </div>
   <input id="image" class="w0" type="file" name="image">
</div>

多图像上传: enter image description here

enter image description here

从文件上传弹出窗口,我想打开一个文件夹“testimages”,然后选择一个图像

如何在SeleniumJava中实现这一点


共 (2) 个答案

  1. # 1 楼答案

    不要点击图像本身,这样弹出窗口就不会出现

    在html代码中,应该有一个类型为file的输入元素。在Selenium测试中,您可以找到输入元素,并用要添加的图像的路径填充它。然后围绕输入元素提交表单

    Selenium框架将为您处理其余的问题。对我来说,它适用于所有浏览器

    我认为这是一个比模拟键盘更干净的解决方案

  2. # 2 楼答案

    据我所见,这是一个窗口对话框,它与浏览器无关,因此无法通过Selenium直接实现自动化。因此,您必须使用Robot/Sikuli/Autoit

    下面的代码是使用“机器人类”的方法。要使用它,请从java.awt包导入所有类,即java。awt。机器人,爪哇。awt。事件KeyEvent,java。awt。工具箱,java。awt。数据传输。StringSelection,java。awt。awt异常以及其他必要的导入:

    编辑了多文件上传的代码(适用于FF、IE和Chrome):

    //Code for clicking on the image button that brings up the window dialog box
      ...
    
    //Putting all the absolute paths of the pics to upload(here, 3 files)
    String arr[] = {"\"D:\\Pic1.jpg\"", "\"D:\\Pic2.jpg\"", "\"D:\\Pic3.jpg\""};
    
    //Copying the path of the file to the clipboard     
    StringSelection photo = new StringSelection(arr[0]+arr[1]+arr[2]); //Putting the path of the image to upload
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(photo, null);
    
    //Pasting the contents of clipboard in the field "File name" of the Window Pop-up
    Thread.sleep(5000); //Some sleep time to detect the window popup
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    
    //To Click on the "Open" button to upload files
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);