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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10076618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:30:34  来源:igfitidea点击:

XPath to find ancestor node containing CSS class

javaxpathselenium

提问by Juan Mendes

I am writing some Selenium tests and I need to be able to find an ancestor of a WebElementthat I have already found.

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

This is what I'm trying but is returning no results

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

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

The image below shows the div that I have selected highlighted in dark blue and the one I want to find with an arrow pointing at it.

下图显示了我选择的 div 以深蓝色突出显示,以及我想找到的带有箭头指向的 div。

enter image description here

在此处输入图片说明

UPDATETried prestomanifesto's suggestion and got the following error

更新尝试了 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

Update 2Really weird, even by ID is not working

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

[cucumber] ? ? ? org.openqa.selenium.NoSuchElementException: Unable to locate element:{"method":"xpath","selector":"./ancestor::div[@id='gridview-1252']"}

Update 3

更新 3

The following XPATH works, but is brittle

以下 XPATH 有效,但很脆弱

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

?

?

回答by Tomalak

This shouldselect the element you want

应该选择你想要的元素

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

In plain English: Of all the ancestor divelements that have ' x-grid-view 'in their class, select the first (closest) one.

通俗地说:在其类中的所有祖先div元素中' x-grid-view ',选择第一个(最接近的)。

Notes:

笔记:

  • I concat spaces as a defensive measure to prevent partial matches.
  • current()is an XSLT function, not an XPath one. It has no meaning outside of XSLT. The current node is expressed as .in XPath.
  • 我连接空格作为防止部分匹配的防御措施。
  • current()是一个 XSLT 函数,而不是一个 XPath 函数。它在 XSLT 之外没有任何意义。当前节点.在 XPath 中表示。