java - 我如何使用 Xpath

标签 java xpath selenium-webdriver

如何使用 Xpath,

这里我的xpath是id('product')/x:tbody/x:tr[1]/x:td[2]

我像这样在我的 Selenium 中使用

driver.findElement(By.xpath("//id('product')/x:tbody/x:tr[1]/x:td[2]")).getText();

但是我收到类似 的错误给定的选择器//id('product')/x:tbody/x:tr[1]/x:td[2] 无效或不会产生 WebElement 。发生以下错误:

有人可以帮助我吗?

我的 HTML 代码是

<table id="product" class="displaytable">

  <thead>
    <tr>
      <th class="hide sorted order1">PRODUCT_ID</th>
      <th class="hide">PRODUCT_NAME</th>
      <th class="hide">ACCESS</th>
    </tr>
  </thead>

  <tbody>
    <tr class="odd">
      <td>1</td>
      <td>Cash</td>
      <td>
        <input type="checkbox" name="productAccess" value="1" checked="checked" id="p1"/>
        <input type="hidden" name="__checkbox_productAccess" value="1" />
      </td>
    </tr>
    <tr class="even">
      <td>2</td>
      <td>Saving</td>
      <td>
        <input type="checkbox" name="productAccess" value="2" checked="checked" id="p2"/>
        <input type="hidden" name="__checkbox_productAccess" value="2" />
      </td>
    </tr>
    <tr class="odd">
      <td>3</td>
      <td>Recurring Deposit</td>
      <td>
        <input type="checkbox" name="productAccess" value="3" checked="checked" id="p3"/>
        <input type="hidden" name="__checkbox_productAccess" value="3" />
      </td>
    </tr>
    <tr class="even">
      <td>4</td>
      <td>Bank Loan</td>
      <td>
        <input type="checkbox" name="productAccess" value="4" checked="checked" id="p4"/>
        <input type="hidden" name="__checkbox_productAccess" value="4" />
      </td> 
    </tr>
    <tr class="odd">
      <td>5</td>
      <td>Recurring Deposit Saving</td>
      <td>
        <input type="checkbox" name="productAccess" value="5" checked="checked" id="p5"/>
        <input type="hidden" name="__checkbox_productAccess" value="5" />
      </td>
    </tr>
  </tbody>
</table>

我点击了特定元素并获取了 Xpath

最佳答案

你的xpath有错误,应该是://table[@id='product']

driver.findElement(By.xpath("//table[@id='product']/tbody/tr[1]/td[2]")).getText()

关于java - 我如何使用 Xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16851253/

相关文章:

java - Android随机数生成器在两个类中的使用

javascript - 在 Chrome 中捕获 JS 错误

java - 从 Selenium 的下拉列表中选择一个项目

javascript - 将 Selenium-IDE 源代码导出为 JavaScript 代码

java - 我如何在java中读取多行文本,行与行之间有空格

java - 在数据库中存储可序列化对象

java - Eclipse插件,自定义运行命令

.net - 从 SQL XML 列中的元素获取属性名称

java - Android - 使用 XPath 从 XML 检索值

php - Xpath setAttribute fatal error 调用成员函数setAttribute