首页 > 解决方案 > 如何使用 Selenium 框架从受用户名和密码保护的站点下载文件?

问题描述

我正在尝试使用 Selenium 从受用户名和密码保护的站点下载文件。

首先,我从下载链接中获得了 href 属性:

WebElement downloadLinkElement = htmlElement.findElement(By.xpath(<xpath_value>));
    String url = downloadLinkElement.getAttribute("href");

其次,我使用 Selenium 网络驱动程序获得了“AUTHSESSION”cookie:

org.openqa.selenium.Cookie cookie = webDriver.manage().getCookieNamed("AUTHSESSION");

然后我构建了一个包含Linux“wget”命令的字符串,就像这样(我为此使用了apache commons exec artifact):

CommandLine cmdLine = new CommandLine("wget");
        cmdLine.addArgument("--cookies=on");
        cmdLine.addArgument("--header");
        cmdLine.addArgument("Cookie: AUTHSESSION=" + cookie.getValue());
        cmdLine.addArgument("-O");
        cmdLine.addArgument("/home/name/Downloads/file.ftl");
        cmdLine.addArgument(url);
        cmdLine.addArgument("--no-check-certificate");

最后,我执行命令,并提取执行输出:

DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);
        executor.setStreamHandler(streamHandler);
        try {
            executor.execute(cmdLine);
        }catch(ExecuteException ee){
            ee.printStackTrace();
            System.out.println(byteArrayOutputStream.toString());
        }

执行后,文件被下载到指定路径。但这不是我们想要的。这是一个 html 文件,其中包含我要从中下载的网站的登录页面。

以下是包含在执行输出中的字符串:

WARNING: cannot verify <ip_address>'s certificate, issued by <company_details>
  Self-signed certificate encountered.
WARNING: no certificate subject alternative name matches
    requested host name ‘&lt;ip_address>’.
HTTP request sent, awaiting response... 302 

一个重要的注意事项是,如果我在 Linux 终端中运行以下命令,则文件下载成功:

wget --cookies on --header "Cookie: AUTHSESSION=<cookie_value>" -O "<download_path>" "<url>"
--no-check-certificate

我错过了什么?

标签: javaseleniumapache-commons-exec

解决方案


所以,我稍微改变了方法。

在初始化 Firefox Web 驱动程序之前,我首先创建一个 FirefoxOptions 对象,如下所示:

    FirefoxOptions firefoxOptions = new FirefoxOptions();
    firefoxOptions.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain");

之后,我将这个对象插入到 Firefox 驱动程序构造函数中:

WebDriver driver = new FirefoxDriver(firefoxOptions);

单击下载链接后,文件将存储在磁盘中,浏览器不会询问任何问题。


推荐阅读