Dims
Dims

Reputation: 51159

Too many results when finding within element with Selenium WebDriver

I did the following search

parts.get(i).findElements(By.xpath("//li[starts-with(@class, '_lessons--row-')]"))

and it returned dozens of results, while I see in Developer Tools, that there are no more than 3 of them.

parts.get(i) returns single WebElement.

Looks like it searches not children of a given element, but over entire page. Can double slash cause this? What double slash means in XPath?

Upvotes: 0

Views: 936

Answers (4)

collder
collder

Reputation: 81

I had a similar case, but . before // didn't help me. Just added findElements(By.xpath("your_xpath")).stream().filter(WebElement::isDisplayed).toList() as a workaround.

Upvotes: 0

NarendraR
NarendraR

Reputation: 7708

// match relative data. which starts at the document root. In your case you are trying to locate using

//li[starts-with(@class, '_lessons--row-')]

So it will return all the match in your html. If you want to locate some specific portion of element with class have start text_lessons--row- . You have to make your xpath more specific.

e.g

 //div[@id='someid']//li[starts-with(@class, '_lessons--row-')]

Upvotes: 0

promitheus
promitheus

Reputation: 77

Try your xpath with .// , normally you should start xpath with "." to stop finding elements from root.

.//li[starts-with(@class, '_lessons--row-')]

Upvotes: 0

Granitosaurus
Granitosaurus

Reputation: 21436

Your xpath is faulty here.

"//li[starts-with(@class, '_lessons--row-')]"

// searches from root level, to search from node preappend .:

".//li[starts-with(@class, '_lessons--row-')]"

Upvotes: 2

Related Questions