java - 如何使用 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 ‘<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 Web 驱动程序之前,我首先创建一个 FirefoxOptions 对象,如下所示:
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain");
之后,我将这个对象插入到 Firefox 驱动程序构造函数中:
WebDriver driver = new FirefoxDriver(firefoxOptions);
单击下载链接后,文件将存储在磁盘中,浏览器不会询问任何问题。
推荐阅读
- winforms - 在无限循环中启动脚本,并有可能停止它
- kubernetes - 对运行在使用 kops 配置的 ec2 上的 kubernetes 集群的只读 kubectl 访问
- ruby-on-rails - Rails,禁用某些控制器的 cookie/会话
- google-data-studio - G Data Studio - forFilterOnly 的用途?
- python - 熊猫,按重复N次的列删除重复项
- bash - 如何使用 bash 脚本创建可执行脚本以逐个运行作业?
- php - 从 PHP 查询 Ms SQL 服务器返回无效名称
- excel - 涉及日期的多条件查找数组的多个匹配项
- protocols - 如何识别与 Modbus 锅炉通信的协议和端口设置
- flutter - 如何在行数据颤动中设置对齐方式?