【问题标题】:XPath to find ancestor node containing CSS classXPath 查找包含 CSS 类的祖先节点
【发布时间】:2012-04-22 00:39:20
【问题描述】:

我正在编写一些 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 有效,但很脆弱

../../../../../../../*

 

【问题讨论】:

  • 你试过用“./”代替“current()/”吗?
  • @prestomanifesto 我刚刚做了,仍然没有得到任何结果...添加了错误消息
  • 该表达式完全合法。出于调试目的,请尝试ancestor::div[1]、ancestor::div[@id='gridview-1252'][1] 等,这将有助于定位中断点。
  • @Tomalak:一定是 selenium 的 xpaths。我尝试了您的建议,但仍然没有找到任何元素,除了我在 Update 3 中显示的内容
  • @downvoter 请通过评论帮助改进问题

标签: java xpath selenium


【解决方案1】:

这应该选择你想要的元素

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

简而言之:在其类中有 ' x-grid-view ' 的所有祖先 div 元素中,选择第一个(最接近的)元素。

注意事项:

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

【讨论】:

  • 对这项工作的支持:我猜我的 selenium 版本不支持/ancestor::
  • @Juan:这将是最不寻常的。您是否找到返回节点的任何 XPath(除了../../* 种类的那些)?
  • 我还没有尝试过你的最新建议./ancestor::*[local-name()='div' and contains(@class, 'x-grid-view')],我会在我的环境准备好再次运行测试时尝试它,我破坏了一些东西......再次感谢
  • Crazy ancestor::*[local-name()='div' and contains(@class, 'x-grid-view')] 似乎可以解决问题。这很奇怪,因为我在其他任何查询中都不需要该资格
  • @Juan 那么这看起来很像 XML 命名空间问题。由于某种原因,您的文档似乎处于 XHTML 模式。这就是你应该挖掘的方向。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多