如何检查曾祖父是否具有包含某个单词的 class 属性?

How to check if great-grandfather has class attribute containing some word?

我有这样的 html 代码:

<div  class='one two three and etc.'>
    <div>
           <div>
                <div class='my_target'>
               </div>
            </div>
    </div>
</div>
例如,

我需要找到 div 和 class="my_target" 的曾祖父 class 包含单词 "two"。我试过这样的表达方式:

//div[../../../[contains(@class,'two')]]

但是没用!有人可以帮助我吗?

最好从另一个方向来解决问题。使用以下表达式:

//div[contains(@class, 'two')]/*/*/div[@class = 'my_target']

这意味着

//div[contains(@class, 'two')]     Select `div` elements anywhere in the document, if
                                   their `class` attribute contains "two"
/*/*/div[@class = 'my_target']     look for any grand-grandchild named `div` whose
                                   `class` attribute value is "my_target"

并且 return

<div class="my_target"></div>

编辑

如果有理由相信 "two" 会出现在不应匹配的其他上下文中(例如 <div class='two-fold'/>),则使用

contains( concat(' ', normalize-space(@class) ,' '), ' two ' )

感谢 Phrogz 的建议。

你很接近。你需要使用这个:

//div[contains(@class, 'my_target'][contains(../../../@class,'two')]

请注意 ../../.. 两边的括号,并且该部分后面没有斜杠。

或者因为只能有

但我会推荐这个替代方案:

//*[contains(@class, 'two')]/*/*/div[contains(@class, 'my_target')]

注意它没有从树上下来然后再爬上去。

旁注: 正如 Phrogz 正确指出的那样,class 名称更可靠的匹配是包围 class 属性和目标 class 空格中的名称:

//*[contains(concat(' ', normalize-space(@class), ' '), ' two ')]/*/*
    /div[contains(concat(' ', normalize-space(@class), ' '), ' my_target ')]

尝试

//div[contains(../../../@class,'two')]

或仅获取 class="my_target" 个元素

//div[contains(@class,'my_target') and contains(../../../@class,'two')]