1

I am using Htmlunit (browser automation/testing tool) to go through a series of links or perform a set of actions on a page. At some point after this I want to see the resulting page in a browser (internet explorer or firefox etc.) How can I do this. ? Thank you Friends...

user329032
  • 41
  • 1
  • 2

4 Answers4

1

I think this is what he had in mind

//Get page as Html <br>
HtmlPage page = wc.getPage("http://stackoverflow.com/");

//create File object <br>
File file = new File("c://temp//out");

//save page image <br>
page.save(file);
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
byronv
  • 11
  • 1
1

I hope I got you correctly.

This is my solution:

WebClient wc = new WebClient();

HtmlPage page = wc.getPage("http://stackoverflow.com/");

//Get page as Html
String htmlBody = page.getWebResponse().getContentAsString();

//Save the response in a file
String filePath = "c:/temp/out.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(htmlBody);
bw.close();

//Open the page with a browser
Runtime.getRuntime().exec("C:/Program Files/Internet Explorer/iexplore.exe " + filePath);

Hope that helps.

Avi Y
  • 2,456
  • 4
  • 29
  • 35
  • It's probably cleaner to use the `java.awt.Desktop` API for opening the web browser, as I suggested in [my answer](https://stackoverflow.com/a/60556796/). The `Desktop.browse(URI)` and `Desktop.open(File)` will launch the default browser for the user's OS (which may be something other than IE even on Windows). – typeracer Mar 06 '20 at 02:46
1

You can also use htmlPage.save(File) (which automatically saves images) before executing real browser

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
0

After saving the page to a file with the HtmlPage.save(File) method, you can use the java.awt.Desktop API to open the file in its default application on your system (i.e. web browser if the file extension is ".html")

Example:

HtmlPage page = webClient.getPage("http://example.com/");
File file = File.createTempFile("example", ".html");
page.save(file);
Desktop.getDesktop().open(file);

This should work on any OS/browser.

Credit: thanks to this answer for suggesting the java.awt.Desktop solution for launching a web browser.

typeracer
  • 759
  • 8
  • 11