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.
But the getElementIndex()
function requires a String locator as parameter. 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?
How to get element index on the basis of its text using Java and Selenium?
5k views Asked by Arka At
2
There are 2 answers
0
On
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
}
Here's the javadoc for
Selenium.getElementIndex()
.It will return an
Number
which is the index of the element selected and takes aString locator
which is used to locate the element you're interested in on the HTML page and can be a number of things eg: -More details here.