Selenium xpath如何通过索引选择集合的节点?

时间:2013-12-23 17:15:14

标签: java selenium xpath

How to select specified node within Xpath node sets by index with Selenium?中提到的答案对我的情况来说已经足够了,但这对我来说不适用于selenium RC - 它不会识别提到的'找不到元素'的xPathes以及selenium IDE。有人知道怎么解决吗?或者也许还有其他方法来编写正确的xpath?

我试过了:

(//table)[1]
(.//table)[1]
.(//table)[1]

此外,selenium无法识别/descendant-or-self::table[1]认为与//descendant-or-self::table[1]很好用,这是另一种表达方式,不幸的是

抱歉无法提供实际的html,但问题是不同的页面具有相同的数据表,可以包含在不同的元素中,例如

<div class='PageContentRight'>
    <div class='DatePicker'></div>
    <div class='PaginationTop'></div>
    <table class='AdminSiteDataTable'></table>
    <div class='PaginationBottom'></div>
    <div></div>
    <div></div>
    <div></div>
    <div class="DataTableWrapper">
        <div class='DatePicker'></div>
        <div class='PaginationTop'></div>
        <table class='AdminSiteDataTable'></table>
        <div class='PaginationBottom'></div>
    </div>
    <div class='SomeDivContainer'>
        <div class='SomeClass1'>
            <div class='SomeClass2'>
                <table class='AdminSiteDataTable'></table>
            </div>
        <div>
    </div>
</div>

这就是为什么我尝试使用一个PageObject AdminSiteDataTable并将表号发送给它的构造函数,它将为当前的PageObject实例设置xPathes。

public AdminSiteDataTable(int tableNumber){ 
    dataTableXpath = String.format("(//table)[%d]", tableNumber); 
    dataTableRowByNumberXpath = "//tr[%d]"; 
    dataTableColumnByNumberXpath = "//td[%d]"; 
    dataTableCellByNumberXpath = dataTableXpath + dataTableRowXpath + dataTableColumnXpath;
    etc.
} 

UPD#1:

如果我使用严格的xpath,我发现它在selenium IDE中有效:

xpath=(//table)[1]//..//..//..//div[@class='PaginatorLine']

但它不适用于WebDriverBackedSelenium,现在尝试修复它。

com.thoughtworks.selenium.SeleniumException: The given selector xpath=(//table)[1]//tbody//tr is either invalid or does not result in a WebElement. The following error occurred:

InvalidSelectorError: Unable to locate an element with the xpath expression xpath=(//table)[1]//tbody//tr because of the following error:
[Exception... "The expression cannot be converted to return the specified type."  

UPD#2: 所以WebDriverBackedSelenium中唯一破碎的方法是getXpathCount(),其余的工作正常,这个选择器是这样的:

private static final String DATA_TABLE = "xpath=(//table)[%d]";

UPD#3: 像这样修复了getXpathCount():

public int xpathCount(String element) {
    logger.debug("Counting xPathes: " + element);
    if (element.contains("xpath=")) {
        return getXpathCount(element.split("xpath=")[1]).intValue();
    }
    return getXpathCount(element).intValue();
}

0 个答案:

没有答案