Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using substring in xpath selenium with Java

I have id's (all divs I am afraid) like this:

<div id ='p1:pdr0'>
<div id = 'p1:pdr0:content'>
<div id = 'p1:pdr0:blahblahblah'>
...

I want just to find the first one. I could use the entire id, but the first part could change. I want to do ends-with(@id,'pdr0') but there is no ends-with().

Someone did suggest using a substring(length-3). I did look up in google. It showed a function but not a specific example of how to use it in an xpath. Would it just be //div[fn:(substring(fn:length(@id)-3))]? Probably not.

Can someone show me an example of using substring and length of an id in an xpath expression? (By the way the exact id names are not exactly that. Suffice to say they all contain the same text but some have more).

like image 704
Tony Avatar asked Mar 03 '26 21:03

Tony


1 Answers

ends-with() is a part of XPath 2.0 and hence cannot be used in your case.

There is contains(), but, if we are talking about pure XPath approach, it would not help since pdr0 is also present in id attributes of other div elements.

Note that, if the order of the div elements is the one you've provided, you can rely on the position of the element (indexing starts from 1):

//div[contains(@id, 'pdr0')][1]

The more reliable option would be to simulate ends-with() using substring() with string-length():

//div[substring(@id, string-length(@id) - 3) = 'pdr0']
like image 163
alecxe Avatar answered Mar 05 '26 11:03

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!