Question

I want to find all elements on a page and just save the one with index X as a variable without having to save all the elements as a list first. I want to do something like this but it gives me the error "The type of the expression must be an array type but it resolved to By".

<ul class="test">
<li name="article"></li>
<li name="article"></li>
<li name="article"></li>
<li name="article"></li>
<li name="article"></li>
</ul>
WebElement article = driver.findElements(By.cssSelector(".test li[name='article']")[2]);

how do I save the 3:d element as a WebElement variable?

Was it helpful?

Solution

WebElement article = driver.findElements(By.cssSelector(".test li[name='article']")).get(2);

Like this. Try using an IDE to understand API misuasage problems easier and faster. By.cssSelector() returns an instance of By, you pass that to findElements which returns an instance of List, on that you can call .get(index) to get a specific element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top