简体   繁体   English

如何使用Java和Selenium在其文本的基础上获取元素索引?

[英]How to get element index on the basis of its text using Java and Selenium?

So there's a table of links on the web page, and I need the element indices. 所以网页上有一个链接表,我需要元素索引。 I know the names of the links. 我知道链接的名称。 I tried the selenium.getElementIndex().intValue() command, hoping for an integer index. 我尝试了selenium.getElementIndex().intValue()命令,希望得到一个整数索引。
But the getElementIndex() function requires a String locator as parameter. 但是getElementIndex()函数需要一个String定位器作为参数。 Not sure what to pass, since the only information about that element that I have is its name. 不确定要传递什么,因为关于该元素的唯一信息是它的名称。 Also, what kind of value does the getElementIndex() return? 此外, getElementIndex()返回什么样的值?

Here's the javadoc for Selenium.getElementIndex() . 这是Selenium.getElementIndex()javadoc

It will return an Number which is the index of the element selected and takes a String locator which is used to locate the element you're interested in on the HTML page and can be a number of things eg: - 它将返回一个Number ,它是所选元素的索引,并带有一个String locator ,用于在HTML页面上找到您感兴趣的元素,并且可以是多种内容,例如: -

  • the id of the element 元素的id
  • some xPath 一些xPath
  • etc 等等

More details here. 更多细节在这里。

This code will return the index of an element relative to it's parent. 此代码将返回元素相对于其父元素的索引。 Only siblings with the same tag will be counted 只有具有相同标签的兄弟姐妹才会被计算在内

int getElementIndex(WebElement element) {
    WebElement parent = element.findElement(By.xpath(".."));
    List<WebElement> siblings = parent.findElements(By.xpath("./" + element.getTagName()));
    int i=0;
    for (WebElement sibling : siblings) {
        if (element.equals(sibling)) {
            return i;
        } else {
            i++;
        }
    }
    throw new NotFoundException(); // Should never happen
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM