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

使用Selenium WebDriver和Java Robot类上传文件,java,selenium,selenium-webdriver,awtrobot,Java,Selenium,Selenium Webdriver,Awtrobot,我正在使用SeleniumWebDriver和Java,我需要自动化文件上传功能。我尝试了很多,但是当点击浏览按钮并打开一个新窗口时,脚本停止进一步执行,反而卡住了。我试过FireFox和IE驱动程序,但都没用 我还尝试调用autoit exe文件,但当单击Browse按钮打开新窗口时,特定语句 Runtime.getRuntime().exec("C:\\Selenium\\ImageUpload_FF.exe") 不能被免除。请帮助这应该适用于Firefox、Chrome和IE驱动程序 F

我正在使用SeleniumWebDriver和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());

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

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
并在upload元素上执行常规类型-

selenium.sendKeys("file path")

我还使用了SeleniumWebDriver和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);
}
这就是我在打开“打开”窗口后所做的:


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

模式对话框打开后,脚本将不起作用,它只是挂起。因此,请先调用
autoit.exe
,然后单击打开模式对话框

这样很好用

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

我想我需要在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);

单击按钮并使用下面的代码。请注意,在路径名中使用了'\\'而不是'\',这对于代码的运行非常重要

通过使用类,您可以使用以下代码上载文件

//测试URL:“https://www.filehosting.org/"
//定位器://输入[@name='upload_file'][@type='file'][1]“
LocalFileDetector=新的LocalFileDetector();
File localFile=detector.getLocalFile(filePath);
RemoteWebElement输入=(RemoteWebElement)driver.findElement(By.xpath(locator));
输入。设置文件检测器(检测器);
input.sendKeys(localFile.getAbsolutePath());
输入。单击();


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

此方法用于设置剪贴板的指定文件路径

  • 将数据复制到剪贴板,如所示。
    • 赢[Ctrl+C]
    • MAC[命令]⌘ + C]-去的路


  • 在查找器窗口中找到文件,然后按
    OK
    选择文件。
    • 赢[Ctrl+V]
    • 苹果
      • “”-命令⌘ + Shift+G
      • 粘贴命令⌘ + V和
      • OK
        将其打开

  • 文件上传测试:-您可以通过单击找到文件


    使用Selenium:sendKeys()当您想要将文件(指本地文件)从本地计算机传输到网格节点服务器时,需要使用setFileDetector方法。通过使用此Selenium,客户端将通过JSON Wire协议传输文件。 有关更多信息,请参阅


    看看这里:,这对我很有效!请更新你的帖子,详细说明“浏览按钮”代表什么。对我来说,第一眼就不那么明显了。提前谢谢。向上投票。我认为,你的答案似乎不完整,这意味着没有正确描述。至少我不知道如何在我的案例中使用它。
     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");
    
    public static void setClipboardData(String filePath) {
        StringSelection stringSelection = new StringSelection( filePath );
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
    }
    
    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;
    }
    
    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();
    }
    
    driver.setFileDetector(new LocalFileDetector());