2

I have a website I need to isolate XPATH identifiers on - they have an XPath ID like this //*[@id="panel-detail-6163748c7952a-partnerCode"]

The issue is that the website changes the value 6163748c7952a on every page load.

Is there any such XPath expression which can match on the first/last part of that string? So of a wildcard like //*[@id="panel-detail-*-partnerCode"]

kjhughes
  • 106,133
  • 27
  • 181
  • 240

2 Answers2

0

This XPath 2.0 expression,

//*[matches(@id, "^panel-detail-.*-partnerCode$")]

or this XPath 1.0 expression,

//*[starts-with(@id, 'panel-detail-') and
    substring(@id, string-length(@id) - string-length('-partnerCode') + 1)  
                                                    = '-partnerCode']

will match all elements whose id attribute value starts and ends with the noted substrings.

See also

kjhughes
  • 106,133
  • 27
  • 181
  • 240
0

There are few methods in xpath such as starts-with or ends-with. Many time folks replaces them with contains which should be discourage.

Please note that ends-with is available with xpath v2.0 .

xpath v1.0 :

//*[starts-with(@id,'panel-detail-') and contains(@id, '-partnerCode')]

xpath v2.0 :

//*[starts-with(@id,'panel-detail-') and ends-with(@id, '-partnerCode')]
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
  • In what way does your answer offer anything beyond that which I'd already answered four hours prior? – kjhughes Oct 11 '21 at 14:42
  • I believe readability. – cruisepandey Oct 11 '21 at 14:45
  • Well, the XPath 1.0 workaround in my answer for the lack of `ends-with()` is hard to read, but it's a standard idiom to achieve the same result. I was just surprised to see you acknowledge that `contains()` should be discouraged in its place as it could also match other than at the end, and then go ahead and use it in your answer anyway. – kjhughes Oct 11 '21 at 15:05
  • @kjhughes : I agree with you that `contains` should be avoided and should have been avoided. But in xpath 1.0 I really do not know how to parse the end sub-string. – cruisepandey Oct 11 '21 at 15:08
  • See my [answer](https://stackoverflow.com/a/69519938/290085) and the referenced Q/A therein for how to effectively do `ends-with()` in XPath 1.0. – kjhughes Oct 11 '21 at 16:06