首页 > 解决方案 > 我在使用 Xpath 定位元素时出错

问题描述

有下面的html。我想使用 xpath 选择特定元素

<tbody>
    <tr role="row" id="gridview-1034-record-ext-record-1" data-boundview="gridview-1034" data-recordid="ext-record-1" data-recordindex="0" class="x-grid-row x-grid-data-row x-grid-row-selected x-grid-row-focused" tabindex="-1">
        <td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1010 x-grid-cell-first x-unselectable " id="ext-gen1139">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">03 Oct 2018</div>
        </td>
        <td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1013 x-unselectable " id="ext-gen1140">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">Sales Quotation</div>
        </td>
        <td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1016 x-unselectable " id="ext-gen1141">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">000079</div>
        </td><td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1019 x-unselectable " id="ext-gen1142">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">ABC Bearings Ltd.</div>
        </td><td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1022 x-unselectable " id="ext-gen1143">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">&nbsp;</div></td><td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1025 x-unselectable " id="ext-gen1144"><div unselectable="on" class="x-grid-cell-inner " style="text-align:right;">8,000.00</div>
        </td><td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1028 x-unselectable " id="ext-gen1145">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">No</div></td>
        <td role="gridcell" class="x-grid-cell x-grid-td x-grid-cell-gridcolumn-1031 x-grid-cell-last x-unselectable " id="ext-gen1146">
        <div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">Approved</div>
        </td>
        </tr>
</tbody>

我无法找到下面的元素并使用下面的代码使用 XPath 来单击它。

帮助将不胜感激

element(by.xpath('//tbody/tr/td/div')).click();
                    expect(div.getText()).toBe('000079');

标签: seleniumselenium-webdriverxpathwebdriverprotractor

解决方案


我同意@Faisal Maqbool 的回答。我会缩短xpath如下,

element = driver.findElement(By.xpath("//div[contains(text(), 'div text you want')]")); element.click();

如果可以,您想尝试直接选择确切的元素,只有在找不到其他选项时才使 xpath 复杂化。


推荐阅读