繁体   English   中英

使用Selenium WebDriver和Java Robot Class进行文件上载

[英]File Upload using Selenium WebDriver and Java Robot Class

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

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

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

无法实现。 请帮助

这适用于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());

我想我需要在亚历克斯的回答中添加一些内容。

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

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

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

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

模态对话框打开后的那一刻脚本将无效,它只是挂起。 因此,首先调用autoit.exe ,然后单击以打开模式对话框。

它像这样工作得很好,

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

通过使用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()上传文件Selenium: sendKeys()Robot Class

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

  1. 将数据复制到ClipBoard为。

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

  1. 在Finder窗口中找到该文件,然后按OK选择该文件。
    • WIN [ Ctrl + V]
    • 苹果电脑
      • Go To Folder ” - 命令⌘ + Shift + G.
      • 粘贴 - 命令⌘ + 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());

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

这是代码:

您将需要这些类和方法:

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

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

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

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

并在上传元素上执行常用类型 -

selenium.sendKeys("file path")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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