计算在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:16:42  来源:igfitidea点击:

Count the number of elements found in selenium python

pythonselenium

提问by Nro

I have the following html page where I am trying to locate the word silverand 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

countis a listof all elements that were found. In order to find its length, you should:

count是找到的所有元素的列表。为了找到它的长度,你应该:

len(count)

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

我强烈建议您阅读文档以更好地了解 Selenium 的工作原理。

回答by Andriy Ivaneyko

It would be quite faster to retrieve count via execute_scriptthen getting lenfrom result of find_elements_bymethod call:

通过execute_script检索计数然后lenfind_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 中找到另一种按文本值检索元素的方法...