如何使用webdriver-selenium从IE浏览器下载文件

时间:2015-04-22 08:54:54

标签: internet-explorer selenium download webdriver

我正在尝试使用webdriver为我的Web应用程序实现下载文件功能。在chrome或firefox中,我们可以设置在单击下载按钮时将文件下载到指定位置的功能,而无需任何窗口提示。

但是在IE 9中,我找不到下载选项的任何功能设置。

在IE中单击下载按钮后,webdriver在窗口提示后挂起以进行保存/打开/取消。单击操作后,Webdriver不会返回任何内容。我不得不退出webdriver并重新创建webdriver对象以继续下一步。

为了处理窗口提示,我尝试使用Sikuli / send key方法等。所有这些仅在窗口处于焦点时才有效。当我运行具有机器锁定的脚本或通过Jenkins运行的远程脚本时,它不起作用。

如何配置IE no以提示保存选项,但将文件下载到任何预定义路径。与IE8一样,我们可以设置regedit来设置下载路径。

2 个答案:

答案 0 :(得分:1)

如果存在文件下载弹出窗口,则Selenium会抛出Modal dialog Present异常。有些时候webdriver会根据弹出窗口后在浏览器上执行的操作而挂起。

如果您需要,可以通过注册表手动完成: http://9to5it.com/internet-explorer-disable-do-you-want-to-open-or-save-this-file-prompt/

如果您使用Java作为编码语言,则可以使用Robot类。请参考以下链接。 How to download .docx file using Selenium webdriver in Java?

c#中的Robot类中没有Java类。我正在使用AutoIT来处理Windows弹出窗口。

希望这有帮助。

答案 1 :(得分:-4)

要在IE浏览器中下载任何文件,最好使用cookie来完成它。请使用cookies,而不是花时间寻找其他方式。

List item
URL myUrl = new URL("linkName");
        URLConnection urlConn = myUrl.openConnection();
        urlConn.connect();
        CookieStore cookieStore = seleniumCookiesToCookieStore();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.setCookieStore(cookieStore);
        HttpGet httpGet = new HttpGet(downloadUrl);
        System.out.println("Downloding file form: " + downloadUrl);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            FileOutputStream fileOutputStream = new FileOutputStream("LocationToSave");
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, read);
            }
            fileOutputStream.close();
            System.out.println("Downloded " + entity.getContentType());
        } else {}