Get the Changed HTML Content After It's Updated by JavaScript? (Htmlunit)

Get the changed HTML content after it's updated by Javascript? (htmlunit)

I figured it out!

HtmlPage objects have an executeJavaScript(String) which can be used to kick off the showTime script. Then, once the script has actually started, that's when waitForBackgroundJavaScript becomes relevant.

The code I ended up with:

import com.gargoylesoftware.htmlunit._
import com.gargoylesoftware.htmlunit.html.HtmlPage
import com.gargoylesoftware.htmlunit.html.DomElement

object AtomicTime {

def main(args: Array[String]): Unit = {
val url = "http://tycho.usno.navy.mil/what.html"
val client = new WebClient(BrowserVersion.CHROME)

var response: HtmlPage = client.getPage(url)
response.executeJavaScript("showTime")

printf("Current AtomicTime: %s", getUpdatedRespose(response, client))
}

def getUpdatedRespose(page: HtmlPage, client: WebClient): String = {
while (page.getElementById("USNOclk").asText() == "Loading...") {
client.waitForBackgroundJavaScript(200)
}
return page.getElementById("USNOclk").asText()
}
}

How to get HtmlUnit to update page after javascript has finished

This is a bug of handling Promise.resolve(), and it has been fixed in SVN.

Please use new WebClient(BrowserVersion.CHROME), with the latest build or snapshot.

There is no need to wait(), as it is not AJAX-based.

How to update content in html using htmlunit?

It's not clear what you want to do exactly, but HtmlUnit is a programmatic browser. Its API allows doing in Java what a user would do with his keyboard and mouse in a standard browser. And modifying the DOM of a web page is not what a user does with his browser.

Its API allows accessing the DOM tree anyway (though not via the W3C DOM interfaces), and you should thus be able to do in Java what you would do in JavaScript with the DOM. HtmlElement instances can be created through the createElement method of HtmlPage. But of course, there is no "JQuery in Java for HtmlUnit".

HtmlUnit How to get a page after executing JavaScript

Yes you are right, the method getNewPage() was removed with the version 2.33 as part of a a huge refactoring regarding event handling.

As replacement you can use the enclosed page of the window.

E.g. if you are sure that the resulting page is in the same window as your current page (has replaced your page without opening a new window), you can use

page.getEnclosingWindow().getEnclosedPage()

If your code might opend up a new window it will be more save to ask the webClient for the current window (newly opened windows are automatically marked as the current)

page.getWebClient().getCurrentWindow().getEnclosedPage()

Or in your code sample you can directly use the client

webClient.getCurrentWindow().getEnclosedPage()

Hope that helps.



Related Topics



Leave a reply



Submit