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

99封情书 提交于 2019-12-25 03:40:21

问题


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]


来源:https://stackoverflow.com/questions/24908876/how-can-i-find-an-element-by-xpath-text-and-the-second-cousin-of-this-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!