Reputation: 294
I've recently come across an issue.
I need to find a div tag on a page, that contain specific text. The problem is, that text is divided into two parts by an inner link tag, so that an HTML tree would look like:
**<html>
<...>
<div>
start of div text - part 1
<a/>
end of div text - part 2
</div>
<...>
</html>**
To uniquely identify that div tag I'd need two parts of div text. Naturally, I would come up with something like this XPath:
.//div[contains(text(), 'start of div text') and contains(text(), 'end of div text')]
However, it doesn't work, the second part can not be found.
What would be the best approach to describe this kind of tag uniquely?
Upvotes: 4
Views: 2936
Reputation: 135
If all you want is the div
element of those child text elements, then you could isolate a piece of unique content from "part 1" and try the following:
//*[contains(., 'part 1')]/parent::div
This way you wouldn't have to think about the div
's attributes.
However, this is usually not best practice. Ideally, you should use the following Xpath in most cases:
//div[@id,('some id') and contains(., 'part 1')]
Upvotes: 0
Reputation: 193108
You were almost there. You simply need to replace the text()
with .
as follows:
//div[contains(., 'start of div text') and contains(., 'end of div text')]
Here is the snapshot of the validation :
Upvotes: 1
Reputation: 52665
try to use below XPath to match required div
by two text nodes:
//div[normalize-space(text())="start of div text - part 1" and normalize-space(text()[2])="end of div text - part 2"]
Upvotes: 3
Reputation: 29362
Well if you have HTML DOM tree like this :
<div id="container" class="someclass">
<div>
start of div text - part 1
<a/>
end of div text - part 2
</div>
</div>
for extracting div text, you can write xpath like this :
//div[@id='container']/child::div
P.S : Writing xpath based on text to find the same exact text is not a good way to write Xpath.
Upvotes: 0
Reputation: 141
This should work:
//div[contains(text(), 'start of div text') and contains(./a/text(), 'end of div text')]
Upvotes: 0