簡體   English   中英

使用Selenium HtmlUnitDriver-headless webdriver上傳文件

[英]File Upload using Selenium HtmlUnitDriver-headless webdriver

我正在嘗試將本地文件(C:\\ sample.txt)上傳到我的服務器。 我嘗試使用Chrome網絡驅動程序來實現這一點,並且它的工作原理絕對不錯。 但是在用HTMLUnitDriver實現相同功能的過程中,我無法從本地磁盤瀏覽文件項。 我也嘗試了以下兩種方法,

1)發送密鑰:

        WebElement inputFile = driver.findElement(By.id("file"));
        System.out.println(driver.getCurrentUrl());
        LocalFileDetector detector = new LocalFileDetector();
        String path = "C:\\UploadSample1.txt";
        File f = detector.getLocalFile(path);
        inputFile.sendKeys(f.getAbsolutePath());

2)使用機器人:

        WebElement browseFile = fluentWait(By.id("browseFile"), driver);
        browseFile.click();
        File file = new File("C:\\UploadSample1.txt");
        driver.switchTo().activeElement();
        StringSelection fileNameToWrite = new StringSelection(
                file.getAbsolutePath());
        Toolkit.getDefaultToolkit().getSystemClipboard()
                .setContents(fileNameToWrite, null);
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        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);

我需要瀏覽文件項,然后只有我才能將其保存到服務器。 因為僅發送文件路徑將在服務器磁盤中搜索文件。 現在我真的被卡住了,無法繼續前進。

非常感謝您的幫助。 謝謝!

如果您需要先瀏覽到文件,恕我直言,這是不可能的; 為此,您將需要AutoIT(不建議使用Robot類)。 因此,最好的選擇是使用sendKeys發送文件路徑。

formInput.setValueAttribute(formValue); 對我來說很好。

程式碼片段:

Iterator<String> formValueIterator =  formValues.keySet().iterator();
while(formValueIterator.hasNext()){
    String formKey = formValueIterator.next();
    String formValue = formValues.get(formKey);

    HtmlInput formInput =  form.getInputByName(formKey);

    if (formInput != null)
        if (formInput instanceof HtmlPasswordInput) {
            ((HtmlPasswordInput)formInput).setValueAttribute(formValue);
        } else {
            formInput.setValueAttribute(formValue);
        }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM