我正在编写一些 Selenium 测试,我需要能够找到我已经找到的 WebElement
的祖先。
这是我正在尝试的,但没有返回任何结果
// checkbox is also a WebElement
WebElement container = checkbox.findElement(By.xpath(
"current()/ancestor-or-self::div[contains(@class, 'x-grid-view')]") );
下图显示了我选择的以深蓝色突出显示的 div 以及我想要查找的带有箭头指向它的 div。
更新 尝试了 prestomanifesto 的建议并得到以下错误
[cucumber] org.openqa.selenium.InvalidSelectorException: The given selector ./ancestor::div[contains(@class, 'x-grid-view']) is either invalid or does not result in a WebElement. The following error occurred:
[cucumber] [InvalidSelectorError] Unable to locate an element with the xpath expression ./ancestor::div[contains(@class, 'x-grid-view']) because of the following error:
[cucumber] [Exception... "The expression is not a legal expression." code: "51" nsresult: "0x805b0033 (NS_ERROR_DOM_INVALID_EXPRESSION_ERR)" location: "file:///C:/Users/JUAN~1.MEN/AppData/Local/Temp/anonymous849245187842385828webdriver-profile/extensions/fxdriv
更新 2 真的很奇怪,连ID都不行
[cucumber] org.openqa.selenium.NoSuchElementException: Unable to locate element:{"method":"xpath","selector":"./ancestor::div[@id='gridview-1252']"}
更新 3
下面的 XPATH 可以工作,但是很脆弱
../../../../../../../*
最佳答案
这应该选择你想要的元素
./ancestor::div[contains(concat(' ', @class, ' '), ' x-grid-view ')][1]
用简单的英语来说:在其类中具有 'x-grid-view '
的所有祖先 div
元素中,选择第一个(最接近的)元素。
注意事项:
- 我将空格作为防止部分匹配的防御措施。
current()
是一个 XSLT 函数,而不是 XPath 函数。它在 XSLT 之外没有任何意义。当前节点在XPath中表示为.
。
关于java - 用于查找包含 CSS 类的祖先节点的 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10076618/