How can i find an element by xpath text() and the

2019-09-01 01:02发布

问题:

I use Htmlunit in java. I need to find an element by text(), and i need the second cousin of this element (i think).

I tried this:

HtmlElement element = page.getFirstByXPath("//*[text() = \"SOMETHING\"]/parent/following-sibling/child");
System.out.println(element.asText()); // it's null

Update: The html source page:

<tr>
    <script>
    _l('its not important')
    </script>
    <td valign="top">
        <font class="its not important">
    </td>
    <td valign="top">
        <font class="its not important">
            SOMETHING
            <script>
                _l('its not important')
            </script>
        </font>
        <script>
            _l('its not important')
        </script>
    </td>
</tr>
<tr>
    <td></td>
    <td valign="top">
        THE INFORMATION I NEED
    </td>
</tr>

回答1:

The following XPath should work:

//tr[td/*[contains(text(), "SOMETHING")]]/following-sibling::tr/td[@valign ="top"]

It will select a <tr> element, which does have a grandchild with the required text. Then it will select all following siblings and select the next element. Please note that I selected the correct <td> element basec on the valign attribute value, you might not want to do that and instead use the position, i.e. td[2]



回答2:

try

//*[text() = \"SOMETHING\"]/../following-sibling::*[1]/*[1]