java - 在java中使用selenium包含或上传文件

标签 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功能时,它会打开上传窗口,但不会选择文件。还有其他办法吗?

最佳答案

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 操作系统中完美运行..

关于java - 在java中使用selenium包含或上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54342231/

相关文章:

python - 当类名以空格开头时,使用 Selenium 解析 html

c# - 将 SelectByText(部分)与 C# Selenium WebDriver 绑定(bind)一起使用似乎不起作用

java - 如何模拟 someObj.meth1(...).meth2(...)?

java - 从客户端调用 servlet

java - 初级 Java if else 范围语句

java - 检索 Playstore 上我的应用程序列表

java - 使用实体管理器删除有时会失败

python - 如何使用 Selenium Webdriver (Python) 在上下文菜单中选择 "save image as..."来保存图像

java - 如何仅使用属性来定位 Selenium 中的元素,而不管属性包含什么值

java - 在 Selenium Webdriver 中,ExpectedCondition.elementToBeClickable 不会等到进度条消失