【问题标题】:Unable to find number of rows in table using Xpath无法使用 Xpath 查找表中的行数
【发布时间】:2015-09-11 13:07:23
【问题描述】:

当我试图在第一个表中查找 tr(class-tr-heading) 的数量时,如果我使用 Xpath(与 CSS Selector-returns 1 tr 一起工作正常),我会得到 2 tr)

<div class="large 20 columns">
  <table class="Red"><tbody>
    <tr class="tr-heading"></tr>
    <tr></tr>
  </tbody></table>
  <table class="Red"><tbody>
    <tr class="tr-heading"></tr>
    <tr></tr>
  </tbody></table>
</div>

一回二回,

    WebElement tbl=dr.findElement(By.xpath("//div[@class='large 20 columns']/table[1]/tbody"));
    List<WebElement> trs=tbl.findElements(By.xpath("//tr[@class='tr-heading']"));
    System.out.println(trs.size());

以下代码返回单个 tr,

WebElement tbl=dr.findElement(By.xpath("//div[@class='large 20 columns']/table[1]/tbody"));
List<WebElement> trs1=tbl.findElements(By.cssSelector("tr[class='tr-heading']"));
System.out.println(trs1.size());

Xpath 似乎占用了整个 div 并返回了两个 tr。请告诉我为什么会有这种差异以及我必须如何使用 xpath。

【问题讨论】:

  • 两个 xpath 都是相同的,所以很明显它会返回 2 作为大小,是的,考虑到整个 div。
  • 为什么不能在一个 xpayh 中找到://div[@class='large 20 columns']/table[1]/tbody/tr[@class='tr-heading']

标签: selenium xpath selenium-webdriver css-selectors


【解决方案1】:

使用点(.)因为它选择当前节点

    WebElement tbl=dr.findElement(By.xpath("//div[@class='large 20 columns']/table[1]/tbody"));
    List<WebElement> trs=tbl.findElements(By.xpath(".//tr[@class='tr-heading']"));
     System.out.println(trs.size());
   //Now it will print out 1 as in the current node there is only one tr tagwith the specified class name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多