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?
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?
Share Improve this question asked Nov 7, 2013 at 12:03 pokeRex110pokeRex110 8552 gold badges14 silver badges28 bronze badges 2- possible duplicate of HTMLUnit executing form with javascript code or HTMLUnit doesn't wait for Javascript – h2ooooooo Commented Nov 7, 2013 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 Commented Nov 7, 2013 at 16:44
2 Answers
Reset to default 3I'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:
- JavaScript not being properly executed in HtmlUnit
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.