4

I am trying get the content of a web page after the execution of the javascript code in the page. Let's suppose for example that I have the following page :

<html>
<body>
  test:
  <div id="inner"></div>
  <script type="text/javascript">
    document.getElementById('inner').innerHTML = "Hello World!";
</script>
</body>
</html>

what I want to extract is the page after the execution of the javascript, so the rendered html :

<html>
<body>
  test:
  <div id="inner">Hello World</div>
</script>
</body>
</html>

Is it possible in htmlUnit?

pokeRex110
  • 833
  • 2
  • 14
  • 26
  • possible duplicate of [HTMLUnit executing form with javascript code](http://stackoverflow.com/questions/16242365/htmlunit-executing-form-with-javascript-code) or [HTMLUnit doesn't wait for Javascript](http://stackoverflow.com/questions/5555178/htmlunit-doesnt-wait-for-javascript/5723773#5723773) – h2ooooooo Nov 07 '13 at 12:04
  • Well, this is not a duplicate. I wait only for the page to load. The script is executed when the page is loaded. Does it have the same ?? – pokeRex110 Nov 07 '13 at 16:44

2 Answers2

3

I'm not sure what issue you are having with that code but it works perfectly for me.

I created a file with that content and the result I got from fetching the content of the page was:

<?xml version="1.0" encoding="ISO-8859-1"?>
<html>
  <head/>
  <body>

  test:

    <div id="inner">
      Hello World!
    </div>
    <script type="text/javascript">
//<![CDATA[

    document.getElementById('inner').innerHTML = "Hello World!";

//]]>
    </script>
  </body>
</html>

This is all the code you need:

WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("the_url");
System.out.println(page.asXml());

You might also find this question useful:

Community
  • 1
  • 1
Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
1

I hope I understood your question correctly. htmlUnit does support execution of JavaScript code.. Check out this tutorial it might help you get started.

Also if you're doing application testing in a professional enviroment, especially if it's on a larger scale, then I would like to advice you to use something a bit more advanced than htmlUnit, for example Selenium.

Dropout
  • 13,653
  • 10
  • 56
  • 109