使用 xpath 获取 table 内的 <tr> 标签计数

Get <tr> tag count within table using xpath

我正在尝试使用 xpath 计算 table 中的 tr 标记行数:

<table class="table">
<tbody>
<tr>...
<tr>...
<tr>...
<tr>...
</tbody>
</table>

我尝试了以下方法,但结果不是 4。任何人都可以帮助我吗?谢谢。

xpath=//*[@class='table']/tbody//tr

Example Script

您为什么限制自己使用 xPath? 如果 HTML 代码在页面上被解析,一个简单的 document.querySelectorAll(".table tr").length; 就可以了。 如果 HTML 是一个字符串,您可以使用正则表达式,如下所示: let rows = str.match(/<tr/g).length;

试试下面的代码 - 确保你使用的是 find elements 而不是 findElement.

driver.findElements(By.xpath("//table[@class='table']/tbody/tr"));

我建议您不要在 XPath 中使用 tbody 标记,因为它可能不存在于页面源代码中,而是由浏览器添加的:

//table[@class='table']//tr