【问题标题】:My XPath is not working for all the scenario我的 XPath 不适用于所有场景
【发布时间】:2021-08-06 04:32:25
【问题描述】:

我需要对表的总数进行断言,并在我为图像表中的总数编写 XPath 时执行此操作,它不适用于所有场景。我知道原因,因为表格是动态的,所以有时它只有 1 个图像,有时它有 5 个图像,所以我很难编写适用于所有场景的 x-path。

对于我写的附加图片:enter image description here WebElement totalElement = driver.findElement(By.xpath("//*[@id="image_table"]/tbody/tr[5]/td[4]")); 它运行良好,但是当表格大小发生变化时。失败了。

网页设计如下,供参考,

***<table class="table table-bordered table-striped table-hover display" id="image_table">
  <tr>
      <td colspan="2" class="text-right">Total</td>
      <td class="text-center">1,650</td>
      <td class="text-center">19,936</td>
      <td class="text-center">21,586</td> (trying to write xpath for this total)
  </tr>***

【问题讨论】:

    标签: html css selenium xpath


    【解决方案1】:

    试试css:

    #image_table>tr>td:last-of-type
    

    它总是定义最后一个元素。

    更新基于评论。这个 css 选择器更健壮:

    #image_table tr:last-of-type>td:last-of-type
    

    【讨论】:

    • 找不到元素。
    • 好的,然后更新你问题中的html代码
    • 它适用于 .//*[@id='image_table']/tbody/tr[position()=last()]/td[4] ,谢谢您的帮助
    • 好的,检查更新的答案。您的定位器仍有小问题。它选择最后一个 tr,而不是最后一个 td。
    【解决方案2】:
    //td[contains(string(),"Total")]/following-sibling::td[last()]
    

    找到包含文本总数的td并找到最后一个td

    【讨论】:

    • //tr[contains(string(),"Total")]/td[last()] 我试过这个但得到 4matches。
    • 用于匹配的
    • 我使用了与您提到的相同的代码并获得以下结果。 1)1,321 2) 1,321 3)21,625 4) 42 从下面我只需要第三个,价值为​​ 21,625。
    • 请添加完整的表格,
    • 用全表更新问题,根据问题中的表格,答案中的定位器有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多