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).

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177

2 Answers2

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;
}
Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
-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.

Margon
  • 511
  • 2
  • 10