Select the parent node containing the text inside the children node

Basically I want to select a node (div) in which it contains the children of the node (h1, b, h3) containing the specified text.

<html>
<div id="contents">
<p>
<h1> Child text 1</h1>
<b> Child text 2 </b>
...
</p>
<h3> Child text 3 </h3>
</div>

I expect / html / div / not / html / div / h 1

I have this below, but unfortunately returns the children instead of the xpath in the div.

expression = "//div[contains(text(), 'Child text 1')]"
doc.xpath(expression)

I expect / html / div / not / html / div / h 1

So, is there a way to do this simply with xpath syntax?

+5
source share
2 answers

You can add "/ .." to bind to the parent element. Not sure if there is a more reliable method.

expression = "//div[contains(text(), 'Child text 1')]/.."
+5
source

The following expression gives node (div), in which any child nodes (and not just h1, b, h3) contain the specified text (and not the div itself):

doc.xpath('//div[.//*[contains(text(), "Child text 1")]]')

div id contents, :

doc.xpath('//div[@id="contents" and .//*[contains(text(), "Child text 1")]]')

, node div ( div), .

+10

All Articles