HTMLUNIT根据表id在HtmlTable中添加行

时间:2013-02-10 00:20:11

标签: html htmlunit

实际上,为了避免jquery的东西,我计划直接在表列表中添加行。

通过在htmltable或其他方式(HTMLUNIT)中将值设置为字符串,可以帮助我动态添加行。

--------------
<table id="list4" class="scroll">
</table>
------------------------

package com.test;

import java.io.IOException;
import java.net.MalformedURLException;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomCharacterData;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableCell;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;

public class TestMain {

  public static void main(String args[])
        throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    final String htmlContent = "<html><head><title>foo</title></head><body><table id='table1'><tr id='row1'><td>cell1</td></tr><tr id='row2'><td>cell2</td></tr><tr id='row3'><td>cell3</td></tr><tr id='row4'><td>cell4</td></tr><tr id='row5'><td>cell5</td></tr><tr id='row6'><td>cell6</td></tr></table></body></html>";
    WebClient webClient = new WebClient();
    final HtmlPage page = loadPage(htmlContent);
    final HtmlTable table = page.getHtmlElementById("list4");
    // want to add to the new row here
    for (final HtmlTableRow row : table.getRows()) {
      System.out.println("Found row");
      for (final HtmlTableCell cell : row.getCells()) {
        System.out.println("   Found cell: " + cell.asText());
      }
    }
  }
}

2 个答案:

答案 0 :(得分:0)

此代码基本上创建了一个新的行和单元格。然后使用一些文本填充单元格,然后将元素附加到其父项。

HtmlTableRow newRow = page.createElement("tr");
HtmlTableCell newCell = page.createElement("td");
Text cellContent = page.createTextNode("Hello World");
newCell.appendChild(cellContent);
newRow.appendChild(newCell);
table.appendChild(newRow); 
// you can also have `table.insertBefore(newRow, exisitingRow);`

答案 1 :(得分:0)

我做了,很少修改。它对我有用。

    final HtmlTable table = page.getHtmlElementById("highlight");

    HtmlTableRow newRow = (HtmlTableRow) page.createElement("tr");
    HtmlTableCell newCell = (HtmlTableCell) page.createElement("td");
    DomText cellContent =  (DomText) page.createTextNode("Welcome Sireesh");

    newCell.appendChild((org.w3c.dom.Node) cellContent);
    newRow.appendChild(newCell);
    table.appendChild(newRow);