1

I am dynamically generating a HTML file in Java Selenium Webdriver. The HTML file has two div tags with each having their own unique id attribute.

I want to dynamically add HTML text to these div tags based upon their id's at a later point in my code.

Can this be achieved? If yes, can someone point me in right direction in regards to how to achieve this? If no, what is an alternative way to achieve this?

I am struggling to tackle this scenario. I really need to be able to dynamically append the data to the HTML page based on div tags.

Thanks in advance!

public void createsummaryfile(String report,String path) throws IOException{            
    File summary;       
    summary = new File(filepath);
    if(!summary.exists()){
        summary.createNewFile();
    }
    BufferedWriter bw = new BufferedWriter(new FileWriter(summary));
    bw.write("<!DOCTYPE html>");
    bw.write("<html><head><h1 align=center>EDC Reports Test Case Execution Summary</h1>");
    bw.write("<style>#report_table{height: 300px;left: 1em;position: relative;top: 5em;width: 300px;}#report{height: 300px;left: 20em;position: relative;top: -15em;width: 300px;}</style></head>");
    bw.write("<body><div id=report_table><table align=center border=1><tbody><tr><th>Report Name</th></tr></div>");
    bw.write("<body><div id=report_display></div>");
    bw.write("</html>");        
    bw.close();
}

public void populate_summary(String report,String path) throws IOException{     
    File summary_report = new File(filepath);
    BufferedWriter br = new BufferedWriter(new FileWriter(summary_report,true));        
    //Here I need to access the div tags by their id's and start appending data     
}
Ketan Deopujari
  • 113
  • 3
  • 3
  • 16
  • 1
    You need to show what you have done thus far. – jgabb Sep 09 '15 at 19:45
  • As of now I have two methods in Java with one method that create the HTML file with its basic layout and the second method is for dynamically appending the data to that HTML file. I wanted to understand if I can somehow access the div tags in second method with their unique id and start appending data or other tags within that div tag. – Ketan Deopujari Sep 09 '15 at 19:49
  • @jgabb Please refer the above code snippet – Ketan Deopujari Sep 09 '15 at 19:54
  • This has nothing to do with Selenium! You need to Google how to properly write XML files - HTML is a superset of XML. – SiKing Sep 09 '15 at 20:17

1 Answers1

0

Finding a div-tag with a specific ID inside your HTML document is possible by creating and searching through the DOM tree.

First you need to create a DOM representation of your document:

public static String addToDivWithID(String htmlDocPath, String divID, String dataToAppend)
        throws ParserConfigurationException, IOException, SAXException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(htmlDocPath);

    Element elementWithID = findDiv(divID, doc.getDocumentElement());

    Element contentToAppend = builder
            .parse(new ByteArrayInputStream(dataToAppend.getBytes()))
            .getDocumentElement();

    elementWithID.appendChild(contentToAppend);

    return domToString(doc);
}

In this example I use this method to find the required div-element: It is performing a recursive lookup (the implementation could look a bit better)

public static Element findDiv(String id, Element element) {

    if( id.equals(element.getAttribute("id")) ) {
        return element;
    }

    NodeList innerDivs = element.getElementsByTagName("div");

    for(int i = 0; i < innerDivs.getLength(); i++) {
        Element current = (Element) innerDivs.item(i);

        if( id.equals(current.getAttribute("id")) ) {
            return current;
        }

        Element possibleChildWithID = findDiv(id, current);

        if(possibleChildWithID != null) {
            return possibleChildWithID;
        }
    }

    return null;
}

After finding the correct element, you can add the new content with these lines (already in the first method):

Element contentToAppend = builder
            .parse(new ByteArrayInputStream(dataToAppend.getBytes()))
            .getDocumentElement();

You can find more about appending XML-strings to a DOM-element here.

Then, you have to transform your DOM-document back to its string representation this way:

public static String domToString(Document doc) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

    return output;
}

More info about transforming DOM-documents to string here.

At last it is a personal concern of mine to mention, that you should not handle your HTML-documents this way! If you want to add content in specific divs, use JSP on the server side like this:

<html>
    <body>
        <div id="first">
            <%
                String first = Foo.getFirstDivStuff();
            %>
            <%= first %>
        </div>
        <div id="second">
            <%
                String second = Foo.getSecondDivStuff();
            %>
            <%= second %>
        </div>
    </body>
</html>

If you want to modify HTML-content which already did its way to the client, use AJAX and a proper JSP or Servlet on the server.

Community
  • 1
  • 1
narranoid
  • 155
  • 2
  • 12