【问题标题】:Can I upload a file using selenium [duplicate]我可以使用 selenium 上传文件吗[重复]
【发布时间】:2020-04-21 18:08:47
【问题描述】:

我尝试使用 selenium 和 java 自动化网站。 但是在网站上有一个从系统上传pdf文件的字段。 如何在 selenium 中上传文件? 这里我附上那个字段的截图Screenshot

【问题讨论】:

标签: java selenium file-upload ui-automation


【解决方案1】:

请看下面的代码,不要通过移动光标或按任意键来改变浏览器的焦点。

public void navigateToWebSiteAndUploadFile() throws UnsupportedFlavorException, IOException, InterruptedException, AWTException {

     // Create a file object 
    File f = new File("resources\\DemoUpload.txt"); 
    // Get the absolute path of file f 
    String absoluteFilePath = f.getAbsolutePath();  
    //Copy the file path to clipboard
    StringSelection  autoCopiedFilePath = new StringSelection(absoluteFilePath);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(autoCopiedFilePath, null); 

    //Navigate to the URL
    driver.get("https://codepen.io/rcass/pen/MmYwEp");
    driver.switchTo().frame("result"); //switching the frame by name
    //Click on a button which opens the popup 
    driver.findElement(By.xpath("//input[@id='fileToUpload']")).click();
    Thread.sleep(2000);
    //This will paste the file path and name in the file explorer by pressing Ctrl +V combination.
    Robot  robot = new Robot(); 
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);  
    // Pause should be used here to perform the action properly and release the  Ctrl +V keys
    Thread.sleep(2000); 
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);  
    Thread.sleep(8000);
    //press enter key after giving the file path.   
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    Thread.sleep(5000);
}

视频链接-https://www.youtube.com/watch?v=WdtqrVeN1Mk&t=19s

【讨论】:

  • 对不起,它不起作用
【解决方案2】:

请试试这个。这个概念通过 Javascript 启用 input 字段并使用它来上传文件。您必须提供choose file 按钮定位器为webelementfilePath,其中文件存在于您的系统中。

 public void uploadFile(WebElement fileElement, String filePath) {
        JavascriptExecutor executor = (JavascriptExecutor) getDriver();
        String activateField = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible'; arguments[0].style.display='block';";

        executor.executeScript(activateField, fileElement);
        executor.executeScript(activateField, fileElement.findElement(By.tagName("input")));
        fileElement.findElement(By.tagName("input")).sendKeys(filePath);
    }

getDriver() 可以替换为您使用driverinstance 的方式。我将它与getDriver() 函数一起使用。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2021-04-10
    • 2012-04-12
    • 2012-10-22
    • 2017-07-28
    • 2011-09-06
    相关资源
    最近更新 更多