0

I'd like to get a reference to the DOM tree (preferably the org.w3c.dom.Document) in order to be able to log the DOM tree in functional tests on a CI service. Search results point to NoClassDefFoundErrors and usage tutorials, but nothing related to the question.

Please note that I'm not looking for a way to retrieve the page source, but the DOM tree including eventual changes after page load since

Get the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page.

(from WebDriver.getPageSource Javadoc).

2 Answers 2

0

The following is quite improvised, but should retrieve the state of the DOM tree with all modifications included:

/**
 * Retrieves the current state of the DOM tree by executing
 * {@code return document.childNodes[1].outerHTML;} in {@code browser}.
 *
 * @throws TransformerConfigurationException if such an expection occurs
 * during the construction of the parser to read the page source of the
 * {@code browser}
 */
public String retrieveDOMTree(JavascriptExecutor browser) throws TransformerConfigurationException,
        ParserConfigurationException,
        SAXException,
        IOException,
        TransformerException {
    String htmlOuterHtml = (String) browser.executeScript("return document.childNodes[1].outerHTML;");
    return htmlOuterHtml;
}
Sign up to request clarification or add additional context in comments.

Comments

-1

My idea:

Retrive the page source of the page as a string:

String pageSource = driver.getPageSource();

Parse it in xml:

Document doc = loadXMLFromString(pageSource);

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

For reference:

How do I load an org.w3c.dom.Document from XML in a string?

Hope it helps you out!

And of course, if you need to trace the dom change, just repeat the sequence.

4 Comments

That's exacly what I excluded in the question. I added a quote why it makes to sense to use this approach (but it was also clear before when you posted the answer).
I found a solution which I'll post in a few minutes.
Yeah you edited the question before my answer! :) Sorry about that!
No, I didn't, (see my explanation in the other comment and the diff view of the edit)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.