Reputation: 5922
Using relative XPath
with Selenium
, is there a way to get the text contents of following-sibling
, using the text contents of both siblings as guidance?
<table class="table">
<tbody>
<tr>
<td>Looking for</td>
<td class="text-right">This!</td>
</tr>
</tbody>
</table>
In the above example, I want to retreive the text snippet This!
based on the text Looking for
.
The path needs to be relative in the sense that these table cells can appear anywhere on the page. The above is a cut-out of the full web page. There can also be other things inserted before inside the same <tr>
block.
I have tried this which seems to find the first cell:
//text()[contains(.,'Looking for')]
However, I'm struggling with how to proceed to get the text in the 2nd sibling.
My attempt has looked something like (incorrectly):
//text()[contains(.,'Looking for')]/following-sibling::text()
Upvotes: 5
Views: 12756
Reputation: 41
You can also use the below to find the 2nd sibling:
//table[@class='table']/descendant::td[last()]
To find find 1st sibling, below can be used:
//table[@class='table']/descendant::td[last()-1]
Upvotes: 1
Reputation: 10559
You can use,
//td[contains(text(),'Looking for')]//following-sibling::td[contains(text(),'This!')]
For more reference on sibling and ancestors click here
Upvotes: 0
Reputation: 503
You almost got it right, here you go, you just needed to show where exactly you want to look for. I hope this helps:
//td[text()="Looking for"]/following-sibling::td[text()="This!"]
Upvotes: 6