2012-05-19 14 views

Odpowiedz

9

Jeśli używasz HtmlUnit, powinieneś mieć stronę Html. Nie można uzyskać HtmlImage i zapisz plik w ten sposób:

HtmlImage image = page.<HtmlImage>getFirstByXPath("//img[@src='blah']"); 
File imageFile = new File("/path/to/file.jpg"); 
image.saveAs(imageFile); 

Jeśli masz URL ... to nie sądzę, trzeba HtmlUnit aby pobrać obraz.

+0

Co jeśli obraz dynamicznie wstawia na stronie html. Na przykład z serwletem? podobnie jak http://example.com/servlet/GetImage&key=1234 –

+1

Proces ten pozostanie niezmieniony, dopóki obraz znajduje się w wynikowej stronie HtmlPage generowanej z wyjścia serwletu. –

0

Oto jak napisałem kod tak:

NodeList nlx = downloadPage.getElementsByTagName("a"); 
for (int y = 0; y<nlx.getLength(); y++) { 
    String ss = nlx.item(y).toString(); 
    if(ss.contains("download/?fileformat=kml")) { 
     System.out.println(ss); 
     HtmlElement anchorAttachment = (HtmlElement)nlx.item(y); 
     InputStream is =anchorAttachment.click().getWebResponse().getContentAsStream(); 
     try { 
      //System.out.println(is); 
      OutputStream out = new FileOutputStream(new File(fileName+".KML")); 

      int read=0; 
      byte[] bytes = new byte[1024]; 
      while((read = is.read(bytes))!= -1) { 
       out.write(bytes, 0, read); 
      } 
      is.close(); 
      out.flush(); 
      out.close();  
      System.out.println("New file created!"); 
     } catch (IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 
} 
Powiązane problemy