复选框单击方法问题(类似xpath) - 使用java的WebDriver

时间:2014-11-25 12:32:30

标签: java jquery selenium xpath selenium-webdriver

Div内有两个不同的Div有一个复选框,所以我想点击复选框(即“divPatPortfolioStatusCount”里面),两个复选框xpath都相似

(i.e By.xpath("//input[@accesskey='2']")

Html代码

<div id="divCreatePortfolio" class="wrapper">
<table class="adminlistfilter" width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr data-bind="if: RowCounts>0, attr: {PortfolioId: Id, DescName:Name}" portfolioid="2" descname="Client-Default">
<td style="width: 5%;">
<input type="checkbox" data-bind="attr: { accesskey: Id }" accesskey="2">
</td>
</tr>
</tbody>
</table>
</div>
<div id="divPatPortfolioStatusCount" class="wrapper">
<table class="adminlistfilter" width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr data-bind="if: RowCounts>0, attr: {StatusId: Id, DescName:Name}" statusid="2" descname="Abandoned">
<td style="width: 5%;">
<input type="checkbox" data-bind="attr: { accesskey: Id }" accesskey="2">
</td>
</tr>
</tbody>
</table>
</div>
</div>

我的Java代码

WebElement statusDiv= driver.findElement(By.id("divPatPortfolioStatusCount"));
WebElement checkBox = statusDiv.findElement(By.xpath("//input[@accesskey='2']"));
checkBox.click();

在“divCreatePortfolio”复选框下执行时,只检查不是“divPatPortfolioStatusCount”让我知道我的xpath问题

4 个答案:

答案 0 :(得分:1)

您需要单独点击这两个不同的复选框,如右下图所示?

//To check Status checkbox
driver.findElement(By.xpath("//div[@id='divCreatePortfolio']//input")).click();
//To check Status count checkbox
driver.findElement(By.xpath("//div[@id='divPatPortfolioStatusCount']//input")).click(); 

答案 1 :(得分:0)

我建议您使用cssnth-child()功能并控制child index来自测试

body>div:nth-child(1) input
body>div:nth-child(2) input

nth-child(1)的数量从1更改为2会找到连续的复选框

答案 2 :(得分:0)

更新我的代码中的xpath

WebElement statusTable = driver.findElement(By
                .xpath("//*[@id='divPatPortfolioStatusCount']/table/tbody"));
        List<WebElement> rows = statusTable.findElements(By.tagName("tr"));
        for (int i = 0; i < rows.size(); i++) {
            WebElement checkBoxSts = driver
                    .findElement(By
                            .xpath("//*[@id='divPatPortfolioStatusCount']/table/tbody/tr["
                                    + i + "]"));
            String statusAccessKey = checkBoxSts.getAttribute("statusid");

            if (statusAccessKey.equals(portfolioId)) {
                WebElement checkbox = driver
                        .findElement(By
                                .xpath("//*[@id='divPatPortfolioStatusCount']/table/tbody/tr["
                                        + i + "]/td[1]/input"));
                checkbox.click();
                break;
            }           
        }

从具有相应状态的数据库中收集statusid并使用参数传递此方法中的statusid,然后继续

答案 3 :(得分:0)

你可以这样做:

List<WebElements> lst = driver.findElements(By.xpath("//input[@accesskey='2']"));
for (WebElement web : lst)
    if(!web.isSelected())
        web.click();

如果你想根据div id选择输入,你可以使用:

//div[@id='divPatPortfolioStatusCount']//input