【问题标题】:File Upload using Selenium WebDriver and Java Robot Class使用 Selenium WebDriver 和 Java 机器人类上传文件
【发布时间】:2011-08-02 09:18:33
【问题描述】:

我正在使用 Selenium WebDriver 和 Java,我需要自动执行文件上传功能。我尝试了很多,但是当单击浏览按钮并打开一个新窗口时,脚本会停止进一步执行,而是卡住。我在 FireFox 和 IE 驱动中都试过了,但都无济于事。

我也尝试通过调用 autoit exe 文件,但是当新窗口在单击浏览按钮时打开时,特定语句

Runtime.getRuntime().exec("C:\\Selenium\\ImageUpload_FF.exe")

无法执行。请帮忙

【问题讨论】:

标签: java selenium selenium-webdriver awtrobot


【解决方案1】:

或者可以使用 webdriver 支持的 selenium -

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

并在上传元素上做通常的类型 -

selenium.sendKeys("file path")

【讨论】:

  • 我认为,您的回答似乎不完整,这意味着没有正确描述。至少我不明白如何在我的情况下使用它。
【解决方案2】:

通过使用RemoteWebElement 类,您可以使用以下代码上传文件。

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


使用 Java Selenium: sendKeys()Robot Class 上传文件。

此方法是将指定的文件路径设置为剪贴板。

  1. 将数据复制到剪贴板。

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

  1. 在 Finder 窗口中找到文件并按 OK 选择文件。
    • WIN [ Ctrl + V ]​​i>
    • MAC
      • "Go To Folder" - Command ⌘ + Shift + G.
      • 粘贴 - Command ⌘ + V 和
      • OK打开它。

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

文件上传测试:-点击Try it Yourself可以找到fileUploadBytes.html文件。

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

使用 Selenium:sendKeys() 当您想从本地计算机传输文件(参考本地文件)到 Grid-Node 服务器时,您需要使用 setFileDetector 方法。通过使用这个 Selenium-Client 将通过 JSON Wire 协议传输文件。 欲了解更多信息,请参阅saucelabs fileUpload Example

driver.setFileDetector(new LocalFileDetector());

【讨论】:

    【解决方案3】:

    单击按钮并使用以下代码。 注意在路径名中使用 '\\' 而不是 '\',这对代码的工作很重要..

    WebElement file_input = driver.findElement(By.id("id_of_button"));
    file_input.sendKeys("C:\\Selenium\\ImageUpload_FF.exe");
    

    【讨论】:

      【解决方案4】:

      模态对话框打开后脚本将不起作用,它只是挂起。所以先调用autoit.exe,然后点击打开模态对话框。

      这样可以正常工作,

       Runtime.getRuntime().exec("Upload_IE.exe");
       selenium.click("//input[@name='filecontent']");
      

      【讨论】:

        【解决方案5】:

        这应该适用于 Firefox、Chrome 和 IE 驱动程序。

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

        【讨论】:

        • 请更新您发布的详细信息“browseButton”代表什么。乍一看,这对我来说并不那么明显。提前致谢。给我点赞。
        【解决方案6】:

        我想我需要在 Alex 的回答中添加一些内容。

        我尝试使用以下代码打开“打开”窗口:

        driver.findElement(My element).click()
        

        窗口打开了,但驱动程序没有响应,代码中的动作甚至没有得到机器人的动作。 我不知道为什么会这样,可能是因为浏览器失去了焦点。

        我让它工作的方式是使用 Actions selenium 类:

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

        【讨论】:

          【解决方案7】:

          我也使用 selenium webdriver 和 java,并且遇到了同样的问题。 我所做的是将路径复制到剪贴板中的文件,然后将其粘贴到“打开”窗口中,然后单击“Enter”。这是有效的,因为焦点始终位于“打开”按钮中。

          代码如下:

          您将需要这些类和方法:

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

          这就是我所做的,就在打开“打开”窗口之后:

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

          就是这样。它对我有用,我希望它对你们中的一些人有用。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-11-08
            • 1970-01-01
            • 2013-09-23
            • 1970-01-01
            • 2013-04-25
            • 1970-01-01
            相关资源
            最近更新 更多