使用Selenium WebDriver和Java Robot类上传文件

ha5z0ras  于 2023-05-12  发布在  Java
关注(0)|答案(8)|浏览(197)

我正在使用Selenium WebDriver和Java,我需要自动化文件上传功能。我尝试了很多,但当单击Browse按钮并打开一个新窗口时,脚本停止进一步执行,而是陷入困境。我尝试了Firefox和IE驱动程序,但无济于事。
我也试着调用一个autoitexe文件,但当点击浏览按钮打开新窗口时,特定的语句

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

无法被原谅。好心帮忙

pu82cl6c

pu82cl6c1#

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

waxmsbnn2#

我想我需要在亚历克斯的回答上加一点东西。
我尝试使用以下代码打开“打开”窗口:

driver.findElement(My element).click()

窗口打开了,但驱动程序变得没有React,代码中的操作甚至没有达到机器人的操作。我不知道为什么会发生这种情况,可能是因为浏览器失去了焦点。
我让它工作的方法是使用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);
qxsslcnc

qxsslcnc3#

点击按钮并使用下面的代码。* 注意在路径名中使用**'\'而不是''**,这对代码的工作 *..

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

xhv8bpkk4#

我也使用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);

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

daolsyd0

daolsyd05#

模态对话框打开后,脚本将无法工作,它只是挂起。因此,首先调用autoit.exe,然后单击以打开模态对话框。
像这样很好用,

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

chhkpiq46#

通过使用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上传文件。

这个方法是将指定的文件路径设置到剪贴板。

public static void setClipboardData(String filePath) {
    StringSelection stringSelection = new StringSelection( filePath );
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
  • 在Finder窗口中找到文件,然后按OK选择文件。
  • WIN [ Ctrl + V ]
  • MAC
  • Go To Folder“- Command + 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());
zpjtge22

zpjtge227#

如果您正在使用Mac,并正在寻找一种与Robot一起工作的简单方法:
1.如果是Mac机,Ctrl+V不起作用,则需要使用cmd+v。(CMD键使用VK_ meta)。
1.您需要为IDE提供特定权限才能访问该设备。请参阅本文获取权限:
机器人keyPress和keyRelease根本不工作
1.当您使用机器人点击上传按钮后打开Java应用程序,浏览器失去焦点(使用CMD+TAB回到上一个应用程序),请使用下面的代码作为我的情况下相同的工作

//click on button to open upload dialog
        driver.findElement(By.xpath("sample/xpath")).click();

        // Create a new Robot instance
        Robot robot = new Robot();
        Thread.sleep(2000);

        //File Need to be imported
        File file = new File("/Users/username/Documents/sampleFile.pdf");
        StringSelection stringSelection = new StringSelection(file.getAbsolutePath());

        //Copy to clipboard
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);

        // 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 CMD+SHIFT+G
        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);
        robot.delay(500);

        //Paste the clipboard value CMD+V
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_META);
        robot.keyRelease(KeyEvent.VK_V);
        robot.delay(500);

        //Press Enter key to close the Goto window and Upload window
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);

        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);

        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);

1.请注意,在每次释放按键后,您需要添加一些延迟以使其工作。此外,按键组合可能因使用情况而异。

3hvapo4f

3hvapo4f8#

或者可以使用支持Selenium的Webdriver-

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

并在upload元素上执行通常的类型-

selenium.sendKeys("file path")

相关问题