简体   繁体   中英

Upload file using Java and Selenium Webdriver

I'm trying to upload a file using Selenium Webdriver and Java.. I have tried many of the suggestions listed such as

    WebElement fileInput = driver.findElement(By.xpath("//div[@class='filepicker dropzone']"));
    fileInput.sendKeys("C:\\Users\\Documents\\Screening.pdf");

as well as the Robot class

    WebElement addFiles = driver.findElement(By.id("add-files"));
    addFiles.click();

    StringSelection filepath = new StringSelection("C:\\Users\\Documents\\Screening.pdf");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filepath, null);

    Robot robot = new Robot();
    Thread.sleep(3000);
    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);

But none of them seem to be working. The robot class opens the windows dialog, but won't interact with it at all.

Here is my what code looks like.

Snippet

I think you need a mix of both, seems like your first statement is searching for the wrong element. Try this:

WebElement addFiles = driver.findElement(By.id("add-files"));
addFiles.sendKeys("C:\\Users\\Documents\\Screening.pdf");

Two suggestions you could try:

1) After the send keys you probably have to click some ok/submit button for that to work.

2) Using the robot: make sure the focus is on that dialog. Possibly you have to press some TAB or alt-TAB to ensure that it is focussed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM