使用Xpath搜索进行改进?

时间:2017-10-26 18:25:15

标签: selenium xpath selenium-webdriver internet-explorer-11

我是学生学习硒并尝试设置一个复选框(通过放置一个勾号)与目标文档位于同一行。以下是该行的外观:

            <span><input>Checkbox</input></span> - <span>_lblDocumentCategoryDescription</span> - <span>_lblDocumentdescription</span>

每一行都包含该行的复选框,类别和说明。我提供了描述,需要在行的开头设置相应的复选框。

虽然我有一个有效的解决方案,但我正在寻找一种更好的方法,因为我的方法非常慢,我可以多次调用它,加快了速度。有问题的页面有315个固定的不同文档,可能会添加(合并和打印功能)。我通常添加至少3行,因此需要运行搜索

我目前正在使用xpath进行搜索,因为我对CSS的了解有限并且看起来像遍历DOM(不:父?)并不容易,除非使用一些javascript,我试图避免。我已经读过执行JS不能正确模拟用户所以我猜xpath是解决方案吗?

据我所知,必须有更快/更好/更有效的解决方案,我希望其他人可能会找到更好的解决方案?

以下是我目前正在使用的内容:

方法调用                 CPTools,setStupidCheckbox(“转租附录”,真实);

方法:

            public CPTools setStupidCheckbox(String documentToPrint, Boolean onIfTrue) {
                    this.log.trace("Starting: setStupidCheckbox; parameter: documentToPrint " + documentToPrint);
                    String xpathForCheckboxes = "/ancestor::tr//input";
                    try {
                        String xpathForDocumentDescriptions = String.format("//span[contains(text(), '%s')]", documentToPrint);
                        tools.waitForElement(By.xpath(xpathForDocumentDescriptions), 2);
                        if (driver.findElement(By.xpath(xpathForDocumentDescriptions)).isDisplayed()) {
                            driver.findElementByXPath(xpathForDocumentDescriptions + xpathForCheckboxes).click();
                        }
                    } catch (org.openqa.selenium.NoSuchElementException | ElementNotVisibleException e) {
                    }
                    this.log.trace("Ending: setStupidCheckbox");
                    return this;
                }

这是表格行的完整xpath(id的动态部分是_ctl316):

            <tr class="DataGridCellData">
                <td class="DataGridCellDataCenterAligned">
                    <span class="DataLabel"><input id="ctl01_PageBody_grdDocument_ctl316_chkSelect" name="ctl01$PageBody$grdDocument$ctl316$chkSelect" onclick="javascript:uiHelper.GridCellCheck(this, 'chkAllSelect');" type="checkbox"></span>
                </td><td>
                    <span id="ctl01_PageBody_grdDocument_ctl316_lblDocumentCategoryDescription">Approval Form</span>
                </td><td align="left">
                    <span id="ctl01_PageBody_grdDocument_ctl316_lblDocumentdescription">Sublease Addendum</span>
                </td><td align="center">
                </td>
            </tr>

提前感谢您提供任何可能的帮助。

1 个答案:

答案 0 :(得分:0)

如果span text(Sublease Addendum)是唯一的,请尝试以下XPath: //td[.='转租附录']