获取使用 XPath 在表格中的 标签计数

huangapple go评论80阅读模式
英文:

Get <tr> tag count within table using xpath

问题

尝试使用XPath来计算以下显示的表格中的tr标签行数:

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

我尝试了上述方法,但结果并未返回4。有人可以帮助我吗?谢谢。

英文:

Im trying to count the number of tr tag rows within the table shown below using xpath:

&lt;table class=&quot;table&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;...
&lt;tr&gt;...
&lt;tr&gt;...
&lt;tr&gt;...
&lt;/tbody&gt;
&lt;/table&gt;

I tried the following but it does not give me 4 as the result. Anyone can help me?. Thanks.

xpath=//*[@class=&#39;table&#39;]/tbody//tr

Example Script

答案1

得分: 1

为什么局限于使用xPath?
如果在页面上解析HTML代码,简单的 document.querySelectorAll(".table tr").length; 就可以工作。
而且如果HTML是一个字符串,你可以使用正则表达式,就像这样:
let rows = str.match(/<tr/g).length;

英文:

Why do you restrict yourself to using xPath?
If the HTML code is parsed on the page, a simple document.querySelectorAll(&quot;.table tr&quot;).length; would work.
And if the HTML is a string, you can use regex, like so:
let rows = str.match(/&lt;tr/g).length;

答案2

得分: 0

尝试以下代码 - 确保使用的是 find elements 而不是 findElement

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

Try the below code - Make sure you are using find elements not findElement.

driver.findElements(By.xpath(&quot;//table[@class=&#39;table&#39;]/tbody/tr&quot;));

答案3

得分: -1

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

//table[@class='table']//tr
英文:

I recommend you to not use tbody tag in your XPath as it might not be present in page source but added by Browser:

//table[@class=&#39;table&#39;]//tr

huangapple
  • 本文由 发表于 2020年9月5日 16:28:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63751927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定