2012-04-09 87 views
6

我正在编写一些Selenium测试,我需要能够找到我已经找到的WebElement的祖先。XPath查找包含CSS类的祖先节点

这就是我想,但没有返回结果

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

下图显示了,我选择了深蓝色和一个我想找到它的箭头指向强调了DIV 。

enter image description here

UPDATE 试图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的作品,但很脆

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

+0

你试过“./”而不是“current()/”吗? – prestomanifesto 2012-04-09 16:53:12

+0

@prestomanifesto我刚刚做了,仍然没有得到任何结果...添加了错误消息 – 2012-04-09 17:02:02

+1

表达式是完全合法的。为了进行调试,可以尝试'ancestor :: div [1]','ancestor :: div [@ id ='gridview-1252'] [1]'等等,这将有助于定位它的中断点。 – Tomalak 2012-04-09 17:07:55

回答

11

应该选择要

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

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

注:

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

努力工作:我的猜测是我的硒版本不支持'/ ancestor ::' – 2012-04-10 16:44:00

+0

@Juan:这将是最*不寻常的。你有没有发现*任何* XPath返回一个节点(除了那些'../../*'变种)? – Tomalak 2012-04-10 16:55:43

+0

我还没有尝试过你的最新建议'./ancestor::[[local-name()='div'和包含(@class,'x-grid-view')]',只要我环境准备再次运行测试,我打破了一些东西......再次感谢 – 2012-04-10 17:22:42