如何使用 Selenium 框架从受用户名和密码保护的站点下载文件?

How can I download a file from a site that is protected with a username and password, using the Selenium framework?

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

首先,我从下载中得到了href属性link:

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 工件):

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 ‘<ip_address>’.
HTTP request sent, awaiting response... 302 

需要注意的是,如果我在Linux终端中运行以下命令,文件下载成功:

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

我错过了什么?

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

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

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

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

WebDriver driver = new FirefoxDriver(firefoxOptions);

点击下载后link,文件保存在磁盘中,浏览器不会询问。