假设以下HTML代码段存在于网页的<body>
元素中的某个位置:
<div id="root_1000" class="root bacon">
<ul>
<li id="item_1234567" class="active">
<div class="userpost author_4281">
<div>This text should be visible.<div>
</div>
<ul><li>Some item</li></ul>
</li>
</ul>
</div>
<div id="root_2000" class="root bacon">
<ul>
<li id="item_8675309" class="active">
<div class="userpost author_3333">
<div>
This text, and as the DIV.root that contains it, should be hidden.
<div>
</div>
<ul><li>Another item</li></ul>
</li>
</ul>
</div>
<div id="root_3000" class="root bacon">
<ul>
<li id="item_7654321" class="active">
<div class="userpost author_9877">
<div>This text should be visible.<div>
</div>
<ul><li>Yet another item</li></ul>
</li>
</ul>
</div>
所以这是我的问题:XPath语法是什么选择包含作者#3333(即div.root
)发布的信息的div[class~="author_3333"]
?
以下XPath语句将正确匹配与我要隐藏的作者#3333相关联的div.userpost
元素,但不包括我需要隐藏的<ul><li>Another item</li></ul>
节点:
.//div[contains(@class, 'author_3333')]
我想要做的是选择与我的XPath语句匹配的节点相关联的最近div.root
个祖先。任何帮助将不胜感激...提前感谢!
答案 0 :(得分:2)
你需要得到第二个div
为其子节点的父节点,如:
//div[.//div[contains(@class, "author_3333")]]
答案 1 :(得分:1)
您可以使用此XPath表达式:
.//div[contains(@class, 'author_3333')]/ancestor::div[contains(@class,'root')][1]
输出为:
<div id="root_2000" class="root bacon">
<ul>
<li id="item_8675309" class="active">
<div class="userpost author_3333">
<div>
This text, and as the DIV.root that contains it, should be hidden.
</div>
</div>
<ul>
<li>Another item</li>
</ul>
</li>
</ul>
</div>