Search code examples
textxpathparenthtmlunitnextsibling

How can i find an element by xpath text() and the second cousin of this element?


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>

Solution

  • 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]