java - 使用 HtmlUnit 下载 javascript 图像
问题描述
如何使用 HtmlUnit下载在Leaflet easyPrint按钮生成的图像?
我正在尝试这样:
public static void main(String[] args) {
try{
WebClient webClient = new WebClient();
HtmlPage test = webClient.getPage("http://rowanwins.github.io/leaflet-easyPrint/");
webClient.waitForBackgroundJavaScript(5000);
final DomElement button = test.getFirstByXPath("/html/body/button");
final InputStream image = button.click().getWebResponse().getContentAsStream();
System.out.println(image);
File file = new File("/home/josue/Basis/STS4/map.png");
copyInputStreamToFile(image, file);
}
catch (Exception e) {
e.printStackTrace();
}
}
private static void copyInputStreamToFile(InputStream inputStream, File file)
throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
}
并得到一个大约 3Kb 的空白 PNG 文件。让它工作的正确方法是什么?
编辑:我想要完成它的原因是为谷歌地图静态 API 获得一个简单的替代方案,我目前已经在一个正在运行的项目中部署了它。
解决方案
我无法让它与 HtmlUnit 一起使用,但使用 Selenium 得到了预期的结果,以防其他人对此功能感兴趣:
public class PG1 {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","/Users/home/Downloads/geckodriver");
FirefoxOptions fxProfile = new FirefoxOptions();
fxProfile.setHeadless(true);
fxProfile.addPreference("browser.download.folderList",2);
fxProfile.addPreference("browser.download.manager.showWhenStarting",false);
fxProfile.addPreference("browser.download.dir","/Users/home/Downloads/");
fxProfile.addPreference("browser.helperApps.neverAsk.saveToDisk","image/png");
driver = new FirefoxDriver(fxProfile);
String baseUrl = "http://rowanwins.github.io/leaflet-easyPrint/";
driver.get(baseUrl);
while(checkForPresenceOfElementByXpath("")) {
}
System.out.println("Loaded");
driver.findElement(By.xpath("/html/body/button")).click();
while(checkForPresenceOfElementByXpath("")) {
}
System.out.println("Downloaded");
driver.close();
}
public static boolean checkForPresenceOfElementByXpath(String xpath){
try{
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(xpath)[last()]")));
return true;
}catch(Exception e){
return false;
}
}
}
推荐阅读
- php - html 代码从 wordpress 后端删除
- git - Git 合并解决符号链接上的冲突
- php - 使用 PHP 的 SAML 2.0 身份验证
- c++ - 假设 a 是双倍的,2.0*a 是否比 2*a 快?
- delphi - 调用 GMLIB.SetCenter 时出现异常
- php - 如何在foreach循环内的php中组合两个数组?
- c++ - Windows上的慢std :: string连接
- c++ - 向 QML 公开 QAbstractModelList 列表
- amazon-dynamodb - DynamoDB MM 邻接列表设计模式 - 删除所有关联?
- reactjs - 如何重定向到另一条路线