在Java中使用Selenium包含或上传文件

时间:2019-01-24 08:26:33

标签: java selenium

<input type="button" class="button white-button custom-modal-button" id="btnAttachment" ng-click="openAttachment()" value="Import CSV template">

enter code here

WebElement browse =driver.findElement(By.xpath("//*[@id=\"btnAttachment\"]"));
//pass the path of the file to be uploaded using Sendkeys method
browse.sendKeys("\\Users\\nilaapps13\\Desktop\\lead.csv");

使用sendkeys功能时,它会打开上传窗口,但不会选择文件。还有其他办法吗?

3 个答案:

答案 0 :(得分:1)

File file = new File("/users/chennai4/downloads/lead.csv");
            StringSelection stringSelection= new StringSelection(file.getAbsolutePath());
           //Copy to clipboard 
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
            Robot robot = new Robot();
          // Cmd + Tab is needed since it launches a Java app and the browser looses focus
            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(1000);
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);

这是我在Mac OS中完美使用的代码。

答案 1 :(得分:0)

我认为您必须按Enter键,即使用sendKeys发送Enter键

答案 2 :(得分:0)

上载窗口是Windows弹出窗口,而不是浏览器弹出窗口,因此在这种情况下,硒命令不起作用。

您可以使用java Robot和StringSelection类。 步骤1:将文件路径复制到系统剪贴板 步骤2:将文件路径粘贴到上传窗口(发送键Ctrl + V),然后发送Enter键。

添加以下软件包

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

使用StringSelection类进行复制和粘贴操作。

StringSelection stringSelection = new StringSelection("\\Users\\nilaapps13\\Desktop\\lead.csv");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);

使用Robot类发送键盘事件

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);