11

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']")
Maroun
  • 94,125
  • 30
  • 188
  • 241
Nro
  • 319
  • 3
  • 4
  • 13

2 Answers2

25

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • thank you actually my code worked all I had to do is the len, the problem with python sometimes is that the error given does not clearly indicate what went wrong, plus I am really new to it. I just dont understand why the question got negative vote, seems like a legit question to me, isnt what this place is for? – Nro Jan 06 '15 at 16:40
  • 1
    @Nro I'm glad it helped. I suggest you to go through the [hep center](http://stackoverflow.com/help) to better understand how Stack Overflow works. We expect minimal understanding of the problem being solved, maybe people downvoted because they expected that at least you know what the function you're using does.. Anyway, I see a well asked question, will upvote. – Maroun Jan 06 '15 at 18:16
0

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 ...

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82