XPath查找包含CSS类的祖先节点

Jua*_*des 8 java selenium xpath

我正在写一些Selenium测试,我需要能够找到一个WebElement我已经找到的祖先.

这是我正在尝试但没有返回任何结果

// checkbox is also a WebElement
WebElement container = checkbox.findElement(By.xpath(
    "current()/ancestor-or-self::div[contains(@class, 'x-grid-view')]") );
Run Code Online (Sandbox Code Playgroud)

下面的图像显示了我选择的深蓝色突出显示的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
Run Code Online (Sandbox Code Playgroud)

更新2 真的很奇怪,即使ID不起作用

[cucumber]       org.openqa.selenium.NoSuchElementException: Unable to locate element:{"method":"xpath","selector":"./ancestor::div[@id='gridview-1252']"}
Run Code Online (Sandbox Code Playgroud)

更新3

以下XPATH有效,但很脆弱

../../../../../../../*
Run Code Online (Sandbox Code Playgroud)

 

Tom*_*lak 17

应该选择你想要的元素

./ancestor::div[contains(concat(' ', @class, ' '), ' x-grid-view ')][1]
Run Code Online (Sandbox Code Playgroud)

用简单的英语:在他们班级中的所有祖先div元素中' x-grid-view ',选择第一个(最近的)元素.

笔记:

  • 我将空间作为一种防御措施,以防止部分匹配.
  • current()是一个XSLT函数,而不是XPath函数.它在XSLT之外没有任何意义.当前节点表示为.XPath.