我怎样才能使用Xpath

时间:2013-05-31 06:44:21

标签: java xpath selenium-webdriver

如何使用Xpath,

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

我在我的硒中使用了这个

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

但我得到的错误如The given selector //id('product')/x:tbody/x:tr[1]/x:td[2] is either invalid or does not result in a WebElement. The following error occurred:

任何人都可以帮助我?

我的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

1 个答案:

答案 0 :(得分:3)

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

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