Reputation: 1959
Disclaimer: I am aware that this question resembles very much XPath to find nearest ancestor element that contains an element that has an attribute with a certain value. Unfortunately, I do not quite understand completely how to select the closest/nearest ancestor?
This is my scenario. I am building an automated test for a webpage displaying several data "tables". Every "table" needs to be identified by its' <label>
content rather than a normal id
-attribute on the "table" (such id
does not exist).
This image illustrates the structure I am working with (snapshot from chrome browser window):
This is essentials from corresponding pseudo html:
<root>
...
<div class="gridBox"> <!-- 1 -->
<div class="gridBox"> <!-- 2 -->
<div class="gridBox"> ... </div>
<div class="gridBox">
<label>In Progress and Rejected</label> <!-- I want to start here -->
</div>
<div class="gridBox">
<div class="gridBox">
<div class="table"> <!-- I want to identify this element -->
<div class="row">
<div class="header">
<div class="column">...</div>
</div>
...
</div>
<div class="row">
<div class="cell">Value 1</div>
<div class="cell">Value 2</div>
...
</div>
</div>
</div>
</div>
</div>
<div class="gridBox">
...
<div class="gridBox">
<label>Await approval</label>
</div>
...
</div>
<div class="gridBox">
...
<div class="gridBox">
<label>Approved</label>
</div>
...
</div>
</div>
...
<root>
Approach
I want <label>In Progress and Rejected</label>
to be the starting point. The next thing I want to do is climb up to this ancestor node: <div class="gridBox"> <!-- 2 -->
. Finally, I want to find the contained descendant child node <div class="table">
. A simple task?
Question
How to identify <div class="gridBox"> <!-- 2 -->
starting from //label[contains(.,"In Progress and Rejected") ]/ancestor::div
?
Upvotes: 1
Views: 1185
Reputation: 111591
I'd use the following::
axis rather than the ancestor::
axis.
This XPath,
//label[normalize-space()="In Progress and Rejected"]
/following::div[@class="table"][1]
selects the first <div class="table">
element following the label
whose space-normalized string value equals the targeted text.
See also Difference between child, following and descendant in XPath axes
Upvotes: 1