File Upload using Selenium WebDriver and Java Robot Class

后端 未结 7 1800
说谎
说谎 2020-11-28 07:19

I am using Selenium WebDriver and Java and I need to automate the file upload feature. I tried a lot, but the moment the Browse button is clicked and a new window opens the

相关标签:
7条回答
  • 2020-11-28 07:40

    I also use the selenium webdriver and java, and had the same problem. What i do is copying the path to the file in the clipboard and then paste it in the "open" window and click "Enter". This is working because the focus is always in the "open" button.

    Here is the code:

    You will need these classes and method:

    import java.awt.Robot;
    import java.awt.event.KeyEvent;
    import java.awt.Toolkit;
    import java.awt.datatransfer.StringSelection;
    
    
    public static void setClipboardData(String string) {
       StringSelection stringSelection = new StringSelection(string);
       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
    }
    

    And that is what i do, just after opening the "open" window:

    setClipboardData("C:\\path to file\\example.jpg");
    //native key strokes for CTRL, V and ENTER keys
    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);
    

    And that´s it. It is working for me, i hope it works for some of you.

    0 讨论(0)
  • 2020-11-28 07:41

    or may use webdriver backed selenium -

    Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
    

    and do the usual type on upload element -

    selenium.sendKeys("file path")
    
    0 讨论(0)
  • 2020-11-28 07:43

    The moment after the modal dialog opens the script will not work, it just hangs. So call autoit.exe first and then click to open the modal dialog.

    It works fine like this,

     Runtime.getRuntime().exec("Upload_IE.exe");
     selenium.click("//input[@name='filecontent']");
    
    0 讨论(0)
  • 2020-11-28 07:43

    By using RemoteWebElement class you can Upload the file using the following code.

    // TEST URL: "https://www.filehosting.org/"
    // LOCATOR: "//input[@name='upload_file'][@type='file'][1]"
    
    LocalFileDetector detector = new LocalFileDetector();
    File localFile = detector.getLocalFile( filePath );
    RemoteWebElement input = (RemoteWebElement) driver.findElement(By.xpath( locator ));
    input.setFileDetector(detector);
    input.sendKeys(localFile.getAbsolutePath());
    input.click();
    


    Upload a file using Java Selenium: sendKeys() or Robot Class.

    This method is to Set the specified file-path to the ClipBoard.

    1. Copy data to ClipBoard as.
      • WIN [ Ctrl + C ]
      • MAC [ Command ⌘ + C ] - way to tell full Path of file.

    public static void setClipboardData(String filePath) {
        StringSelection stringSelection = new StringSelection( filePath );
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
    }
    

    1. Locate the file on Finder Window and press OK to select the file.
      • WIN [ Ctrl + V ]
      • MAC
        • "Go To Folder" - Command ⌘ + Shift + G.
        • Paste - Command ⌘ + V and
        • press OK to open it.

    enum Action {
        WIN, MAC, LINUX, SEND_KEYS, FILE_DETECTOR;
    }
    public static boolean FileUpload(String locator, String filePath, Action type) {
        WebDriverWait explicitWait = new WebDriverWait(driver, 10);
    
        WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( By.xpath(locator) ));
        if( type == Action.SEND_KEYS ) {
            element.sendKeys( filePath );
            return true;
        } else if ( type == ActionType.FILE_DETECTOR ) {
            LocalFileDetector detector = new LocalFileDetector();
            File localFile = detector.getLocalFile( filePath );
            RemoteWebElement input = (RemoteWebElement) driver.findElement(By.xpath(locator));
            input.setFileDetector(detector);
            input.sendKeys(localFile.getAbsolutePath());
            input.click();
            return true;
        } else {
            try {
                element.click();
    
                Thread.sleep( 1000 * 5 );
    
                setClipboardData(filePath);
    
                Robot robot = new Robot();
                if( type == Action.MAC ) { // Apple's Unix-based operating system.
    
                    // “Go To Folder” on Mac - Hit Command+Shift+G on a Finder window.
                    robot.keyPress(KeyEvent.VK_META);
                    robot.keyPress(KeyEvent.VK_SHIFT);
                    robot.keyPress(KeyEvent.VK_G);
                    robot.keyRelease(KeyEvent.VK_G);
                    robot.keyRelease(KeyEvent.VK_SHIFT);
                    robot.keyRelease(KeyEvent.VK_META);
    
                    // Paste the clipBoard content - Command ⌘ + V.
                    robot.keyPress(KeyEvent.VK_META);
                    robot.keyPress(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_META);
    
                    // Press Enter (GO - To bring up the file.)
                    robot.keyPress(KeyEvent.VK_ENTER);
                    robot.keyRelease(KeyEvent.VK_ENTER);
                    return true;
                } else if ( type == Action.WIN || type == Action.LINUX ) { // Ctrl + V to paste the content.
    
                    robot.keyPress(KeyEvent.VK_CONTROL);
                    robot.keyPress(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_CONTROL);
                }
    
                robot.delay( 1000 * 4 );
    
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
                return true;
            } catch (AWTException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    

    File Upload Test :- You can find fileUploadBytes.html file by clicking on Try it Yourself.

    public static void uploadTest( RemoteWebDriver driver ) throws Exception {
        //driver.setFileDetector(new LocalFileDetector());
        String baseUrl = "file:///D:/fileUploadBytes.html";
        driver.get( baseUrl );
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    
        FileUpload("//input[1]", "D:\\log.txt", Action.SEND_KEYS);
    
        Thread.sleep( 1000 * 10 );
    
        FileUpload("//input[1]", "D:\\DB_SQL.txt", Action.WIN);
    
        Thread.sleep( 1000 * 10 );
    
        driver.quit();
    }
    

    Using Selenium: sendKeys() When you want to transfer a file (Refer a local file) form your local computer to the Grid-Node server, you need to use setFileDetector method. By using this Selenium-Client will transfer the file through the JSON Wire Protocol. For more information see saucelabs fileUpload Example

    driver.setFileDetector(new LocalFileDetector());
    
    0 讨论(0)
  • 2020-11-28 07:50

    This should work with Firefox, Chrome and IE drivers.

    FirefoxDriver driver = new FirefoxDriver();
    
    driver.get("http://localhost:8080/page");
    
    File file = null;
    
    try {
        file = new File(YourClass.class.getClassLoader().getResource("file.txt").toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    
    Assert.assertTrue(file.exists()); 
    
    WebElement browseButton = driver.findElement(By.id("myfile"));
    browseButton.sendKeys(file.getAbsolutePath());
    
    0 讨论(0)
  • 2020-11-28 07:50

    I think I need to add something to Alex's answer.

    I tried to open the Open window by using this code:

    driver.findElement(My element).click()
    

    The window opened, but the driver became unresponsive and the actions in the code didn't even get to the Robot's actions. I do not know the reason why this happens, probably because the browser lost focus.

    The way I made it work was by using the Actions selenium class:

     Actions builder = new Actions(driver);
    
     Action myAction = builder.click(driver.findElement(My Element))
           .release()
           .build();
    
        myAction.perform();
    
        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);
    
    0 讨论(0)
提交回复
热议问题