计算在 selenium python 中找到的元素数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27788397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count the number of elements found in selenium python
提问by Nro
I have the following html page where I am trying to locate the word silver
and keep count on how many were found.
我有以下 html 页面,我试图在其中找到这个词silver
并计算找到了多少。
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']")
采纳答案by Maroun
回答by Andriy Ivaneyko
It would be quite faster to retrieve count via execute_scriptthen getting len
from result of find_elements_by
method call:
通过execute_script检索计数然后len
从find_elements_by
方法调用的结果中获取会更快:
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 innerTextSO question ...
上面的示例适合您如果您使用 jQuery,则可以在How to get element by innerTextSO question 中找到另一种按文本值检索元素的方法...