Nro
Nro

Reputation: 349

Count the number of elements found in selenium python

I have the following html page where I am trying to locate the word silver and keep count on how many were found.

This is just two showing here but it can generate more so I don't know the exact count.

<tr id="au_4" class="odd">
<td>Silver</td>
</tr>
<tr id="au_4" class="even">
<td>Silver</td>
</tr>

This is what I tried but no luck:

count =  driver.find_elements_by_xpath("//td[text()='Silver']")

Upvotes: 12

Views: 42801

Answers (2)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

It would be quite faster to retrieve count via execute_script then getting len from result of find_elements_by method call:

script = "return $(\"td:contains('{}')\").length".format(text="Silver")
count = driver.execute_script(script)

Sample above suits to you If you use jQuery, another ways of retrieving elements by text value can be found in How to get element by innerText SO question ...

Upvotes: 0

Maroun
Maroun

Reputation: 95958

count is a list of all elements that were found. In order to find its length, you should:

len(count)

I highly recommend you to go through the docs to better understand how Selenium works.

Upvotes: 25

Related Questions