无法使用 xpath 获取正确的定位器

Not able to fetch the right locator using xpath

我尝试了一些 xpath 并显示了多个结果。我希望找到颜色为 'Red' 的 'LinkA' 按钮的定位器。我想在这里使用任何其他 xpath 吗?请任何解决方案

这是我的代码:

<table>
<thead>
    <tr>
        <th>Color</th>
        <th>LinkName</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <span>
            <button>
                <span>Red</span>
            </button>
            </span>
        </td>
        <td>
            <span>
            <button>
                <span>LinkA</span>
            </button>
            </span>
        </td>
    </tr>
    <tr>
        <td>
            <span>
            <button>
                <span>Yellow</span>
            </button>
            </span>
        </td>
        <td>
            <span>
            <button>
                <span>LinkA</span>
            </button>
            </span>
        </td>
    </tr>
    <tr>
        <td>
            <span>
            <button>
                <span>Green</span>
            </button>
            </span>
        </td>
        <td>
            <span>
            <button>
                <span>LinkA</span>
            </button>
            </span>
        </td>
    </tr>
</tbody>
</table>

enter image description here

这个 XPath 应该可以工作:

//td//span[contains(text(),'Red')]]/following-sibling::td//span

从字面上看,它发现 td 包含 span,包含 Red 文本。 然后如果转到包含所需 LinkA

的以下兄弟 td

这个

//span[text()='Red']/ancestor::td/following-sibling::td/descendant::button

//span[text()='Red']/ancestor::td/following-sibling::td/descendant::button/span[text()='LinkA']

应该足够了。

请检查 dev tools (Google chrome) 我们是否在 HTML DOM 中有 unique 条目。

你应该检查的 xpath :

///span[text()='Red']/ancestor::td/following-sibling::td/descendant::button/span[text()='LinkA']

检查步骤:

Press F12 in Chrome -> 转到 element 部分 -> 执行 CTRL + F -> 然后粘贴 xpath 并查看是否需要 element正在 突出显示 1/1 匹配节点。

如果我们有 1/1 匹配节点,请确保:

  1. 此 div 不在 iframe 下。
  2. 此 div 不在影子根下。
  3. 你不应该在 selenium 推出的新 tab/windows 上。