我是用JAVA写seleium做自动化的,最近遇到一个问题足足困扰了两天,就是想用Js来下载DPF文件转base64,但是遇到各种坑,最终是在老同事的代码中找到解决方法,本文是JAVA代码,前端可绕道了(或参考第二行写法)
直接上代码
private String getOrderContentJs(String href){
return "function getJs(){let xhr=new XMLHttpRequest();xhr.open('get','" + href + "');xhr.responseType='blob';xhr.onreadystatechange=function(){if(xhr.readyState===4&&xhr.status===200){var blob=new Blob([xhr.response],{type:'text/html'});let reader=new FileReader();reader.readAsDataURL(blob);reader.οnlοad=function(readerEvt){var binaryString=readerEvt.target.result;window.textData=binaryString}}};xhr.send('" + href + "')}getJs()";
}
private File doDownloadPDFFile(WebDriver driver, String url, String fileName) throws Exception {
((JavascriptExecutor) driver).executeScript(getOrderContentJs(url));
String content = "";
for (int i = 0; i < 10; i++) {
Object returnObj = ((JavascriptExecutor) driver).executeScript("return window.textData");
if (ObjectUtils.isNotEmpty(returnObj)) {
content = returnObj.toString();
break;
}
sleep(5000L);
}
if (StringUtils.isEmpty(content)) {
return null;
}
String fileStr = content.split(",")[1];
File file = new File(fileName);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
base64ToFile(fileStr, file);
return file;
}