使用HtmlUnit下载JavaScript图像 [英] Downloading javascript image with HtmlUnit
本文介绍了使用HtmlUnit下载JavaScript图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用HtmlUnit下载在 Leaflet easyPrint 按钮生成的图像?
How do I go about downloading the image generated at Leaflet easyPrint button using HtmlUnit?
我正在这样尝试:
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文件. 使它正常工作的正确方法是什么?
And getting a blank PNG file with about 3Kb. What is the proper way to get it working?
编辑:我要完成此操作的原因是,它是Google Maps静态API的一种简单替代方案,目前我已在运行中的项目中对其进行了部署.
EDIT: The reason I want to accomplish it, is to get a simple alternative for Google Maps static API, which I currently have deployed in a running project.
推荐答案
在其他人对此功能感兴趣的情况下,我无法使其与HtmlUnit一起使用,但使用Selenium可获得了预期的结果:
I couldn't get it to work with HtmlUnit, but got the expected result using Selenium, in case someone else is interested in this feature:
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;
}
}
}
这篇关于使用HtmlUnit下载JavaScript图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文