繁体   English   中英

如何处理Windows基本文件下载弹出并使用Selenium和Java保存文件?

[英]how to handle windows base file download pop up and save file with selenium and java?

public static FirefoxProfile FirefoxDriverProfile() throws Exception {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.download.folderList", 2);
    profile.setPreference("browser.download.manager.showWhenStarting",false);
    profile.setPreference("browser.download.dir",Constant.downloadPath);
    profile.setPreference("browser.helperApps.neverAsk.openFile",
               "text/csv;application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
               "text/csv;application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.download.manager.focusWhenStarting", false);
    profile.setPreference("browser.download.manager.useWindow", false);
    profile.setPreference("browser.download.manager.showAlertOnComplete",false);
    profile.setPreference("browser.download.manager.closeWhenDone", false);
    profile.setPreference("pdfjs.disabled", true);

    return profile;
}

@Test
public static synchronized WebDriver getDriverInstance(String browser) throws Exception{
    // If the browser is Firefox, then do this
    if (Constant.BROWSER_FIREFOX.equalsIgnoreCase(browser)) {

        fd = new FirefoxDriver(FirefoxDriverProfile());
        fd.manage().window().maximize();
        fd.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

    }
}

上面是我的代码,用于自动下载文件而不显示弹出窗口的代码,但是它不起作用。 我从各种站点和stackoverflow上给出的答案中获取了参考。 我是硒新手。

如果那是您所有的代码,我不明白您希望它如何下载任何内容。 尝试使用Robot()代替强制禁用Windows。 这是我的此类代码示例:

public static void copyPaste (String content) throws AWTException {
    //store the path (that you passing as 'content' String) to the saving folder in RAM
    StringSelection selection = new StringSelection(content);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(selection, selection);

    //Initialize Robot()
    Robot robot = new Robot();

    //wait some time for save dialog to open
    robot.delay(3000);

    //imitate user's action - paste what you stored in RAM previously
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);

    //submit this and download should start
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
}

打开下载窗口对话框后,可以使用此方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM