1

使用 HtmlUnit,我应该如何抓取隐藏 div 下的元素(样式 =“显示:无”)?

在这种情况下,我试图获取表中显示的字段的值。第一个单元格是字段名称,第二个单元格是值。我正在使用“for”属性来查找关联的值。

HTML:

<div style="display: none;" id="tab-doc-div">
<div class="tab-container" align="center">
    <table class="datatable">
        <tbody>
            <tr>
                <th rowspan="1" colspan="1">
                    &nbsp;<label for="doc.change.stat">
                    <font color="">*&nbsp;</font>Action</label>
                </th>
                <td colspan="2">
                    Data Change (DTA)
                </td>
            </tr>
        </tbody>
    </table>
</div>

我正在使用的 Java/HtmlUnit 代码:

public static String getTextForProperty(HtmlPage page, String property) throws Exception {
    List<HtmlLabel> labels = (List<HtmlLabel>)page.getByXPath("//label[@for='" + property + "']");

    if (labels.isEmpty()) {
        return null;
    } else {
        return labels.get(0).getParentNode().getNextSibling().asText();
    }
}
String myValue = getTextForProperty(myPageObject, "doc.change.stat"); //returns null
4

2 回答 2

0

我会使用 getAttribute(String attributeName) http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/html/DomElement.html#getAttribute(java.lang.String )

例子 :

for (HtmlLabel label : labels) {
if (!label.getAttribute("for").isEmpty()) {
myValue = label.getAttribute("for");
}
于 2012-06-28T10:46:47.553 回答
0

鉴于您的示例 HTML 文件和您对另一个答案的评论:

在我的示例中,我想获得“数据更改(DTA)”作为结果

这就是你所需要的:

HtmlTableCell td = page.<HtmlTableCell>
                     getFirstByXPath("//label[@for='doc.change.stat']/../../td");
System.out.println(td.getTextContent().trim());
于 2012-06-28T16:19:03.813 回答