查找相对于另一个 WebElement 的 WebElement

Finding WebElement Relative to Another WebElement

我试图找到一个与另一个网络元素相关的网络元素,而另一个网络元素不是 child 使用 Selenium 的另一个网络元素。这是我正在使用的源代码片段...

<td class="action" rowspan="7">
    <table class="action">
        <tbody>
            <tr class="topTr topTrPlainBg">
            <tr>
                <td class="middleLeftPlainBg" style="width: 4px;">
                <td class="caption" style="width: 99%; height: 215px;" colspan="4" title="Action properties">
                    <a href="javascript: var none=0;">Foo bar</a>
                </td>
                <td class="middleRightPlainBg" style="width: 4px;">
            </tr>
            <tr class="bottomTr bottomTrPlainBg">
        </tbody>
    </table>
</td>
<td class="rule rulePlainBg" colspan="1">
    <table class="rule rulePlainBg">
        <tbody>
            <tr>
                <td class="captionRule">Successful</td>
                <td class="plus">
                    <img src="https://mcc-69-77.usae.bah.com/sam/admin/vpe2/public/img/vpe-old/rule/plus-over.gif" title="Add item"/>
                </td>
                <td class="swap">
            </tr>
        </tbody>
    </table>
</td>

我正在尝试查找与值为 "Foo bar" 的 a 元素相关的标题为 "Add item" 的 img 元素。我知道我要查找的元素将是 td 的 child,紧跟在 td 之后,即相对元素的 parent。这是我目前所拥有的(Java)...

WebElement fooBar = driver.findElement(By.linkText("Foo bar"));
fooBar.findElement(By.xpath("..//..//..//..//../td//img[@title='Add item']")).click();

知道我做错了什么吗?我试过使用斜线,但什么都做不了。

查看您正在使用的 xpath 我所看到的是您缺少初始 // 因此请将您正在使用的 xpath 替换为

//..//..//..//..//../td//img[@title='Add item']

如果稍微改变策略并使用 following-sibling:

会怎么样
//td[@class="action" and .//td[@class="caption"]/a[. = "Foo Bar"]]/following-sibling::td[contains(@class, "rule")]//td[@class="plus"]/img[@title="Add item"]

在硒中:

WebElement addItem = driver.findElement(By.xpath("//td[@class='action' and .//td[@class='caption']/a[. = 'Foo Bar']]/following-sibling::td[contains(@class, 'rule')]//td[@class='plus']/img[@title='Add item']"));
addItem.click();

这里我们正在获取 a 元素,其中 Foo Bar 文本正在检查 parent 的 classes。然后,对于第一个 td parent 获得以下 td 兄弟 rule class。然后,获取所需的 img 元素。

如果你想从找到的 a 元素开始,使用 ancestor 找到 td parent 和 class="action" 然后应用以下兄弟姐妹检查:

ancestor::td[@class="action"]/following-sibling::td[contains(@class, "rule")]//td[@class="plus"]/img[@title="Add item"]

在硒中:

WebElement fooBar = driver.findElement(By.linkText("Foo bar"));
fooBar.findElement(By.xpath("ancestor::td[@class='action']/following-sibling::td[contains(@class, 'rule')]//td[@class='plus']/img[@title='Add item']")).click();