我可以使用硒上传文件吗

时间:2020-01-03 06:32:53

标签: java selenium file-upload ui-automation

我试图使用带有Java硒的网站来自动化。 但是在网站上,有一个用于从系统上传pdf文件的字段。 如何在硒中上传文件? 在这里,我附上了该字段Screenshot

的屏幕截图

2 个答案:

答案 0 :(得分:0)

请参见以下代码,不要通过移动光标或按任何键来更改浏览器的焦点。

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

答案 1 :(得分:0)

请尝试这个。此概念通过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()可以用您使用driver实例的方式替换。我正在使用getDriver()函数。

希望它会对您有所帮助。