在WebDriver中获取正确的WebElement

时间:2012-07-03 11:35:19

标签: java selenium webdriver

我有一个大致如下的HTML页面:

<div id="rolesRollerBody" style="height: 309px;">
    <input type="checkbox" onclick="checkAll('removeRolesForm');" name="allbox">
    Select all
    <br><br>
    <input type="checkbox" value="49893" name="delRole">
    CCC11
    <br>
    <input type="checkbox" value="49881" name="delRole">
    TEST111
    <br><br>
</div>

我使用以下方式获取整个面板:

WebElement deletePanel = driver.findElement(By.className("bulkUpdateBody"))
            .findElement(By.id("rolesRollerBody"));

现在我需要获取名为'TEST111'的复选框。问题是,我无法获得文本'TEST111'。

1 个答案:

答案 0 :(得分:2)

XPath解决方案:

id('rolesRollerBody')/text()[contains(.,'TEST111')]/preceding-sibling::input[1]

这选择:

input                          - The `input` element
/preceding-sibling::input[1]   - that is most closely followed by
/text()[contains(.,'TEST111')] - the 'TEST111' text
id('rolesRollerBody')          - in the element with id 'rolesRollerBody'.

或者,按直接顺序:

id('rolesRollerBody')          - The element with id 'rolesRollerBody'
/text()[contains(.,'TEST111')] - in that, the text node containing 'TEST111'
/preceding-sibling::input[1]   - and the first preceding `input` element to that text

因此,

WebElement theInput = driver.findElement(By.xpath("id('rolesRollerBody')/text()[contains(.,'TEST111')]/preceding-sibling::input[1]"));