一种可能的解决方案是通过Selenium获取文件的URL,创建(非Selenium)连接,将Selenium的cookie复制到该连接(如果需要),然后下载文件。大多数语言都有用于执行HTTP请求的API(或库)。例如,要在Java中完成此操作,可以使用URL.openConnection():
String link = linkElement.getAttribute("href");
URL url = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
为了模仿Selenium用户,您可能需要复制Selenium拥有的cookie(例如,如果您正在测试需要登录的网站)。
Set cookies = webDriver.manager().getCookies();
String cookieString = "";
for (Cookie cookie : cookies) {
cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}
httpURLConnection.addRequestProperty("Cookie", cookieString);
然后,您可以HttpURLConnection.getInputStream()用来将文件内容写入您的首选位置。
try (InputStream in = httpURLConnection.getInputStream()) {
Files.copy(in, new File("/path/to/file.ext").toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
尽管对于不同的编程语言,此方法可能会有所不同,但对于所有浏览器,其工作方式都是相同的。