[英]Finding WebElement Relative to Another WebElement
我試圖找到一個相對於另一個 webelement 的 webelement,該 webelement 不是另一個使用 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
元素查找標題為“添加項目”的img
元素。 我知道我正在尋找的元素將是緊跟在相關元素父元素td
之后的td
的子元素。 這是我到目前為止所擁有的(在 Java 中)......
WebElement fooBar = driver.findElement(By.linkText("Foo bar"));
fooBar.findElement(By.xpath("..//..//..//..//../td//img[@title='Add item']")).click();
任何想法我在這里做錯了什么? 我試過稍微玩弄斜線,但什么也做不了。
如果您稍微改變策略並使用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();
在這里,我們正在獲取帶有Foo Bar
文本的a
元素,在途中檢查父類的類。 然后,對於第一個td
父級,獲得以下具有rule
類的td
兄弟級。 然后,獲取所需的img
元素。
如果你想從找到的a
元素開始,使用ancestor
找到class="action"
的td
父元素,然后應用以下兄弟檢查:
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();
查看您正在使用的xpath
,我看到的是您缺少初始值//
因此請替換您正在使用的xpath
//..//..//..//..//../td//img[@title='Add item']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.