Reputation: 25
I'm trying to locate the below element using Selenium:
<a class="ABC" href="#" data-test-id="XXX|YYY|ZZZ">
There are multiple elements on the page with "ABC", "XXX", "YYY" and "ZZZ", but my key words are "ABC" and "ZZZ". So in order to target this element precisely, I need to write something like:
//input[@class="ABC"] AND //*[contains(@data-test-id,'ZZZ')]")
Is there a way to write this in a single XPath?
Upvotes: 2
Views: 563
Reputation: 111696
You can write compound predicates in XPath as follows:
//a[@class='ABC' and contains(@data-test-id,'ZZZ')]
or
//a[@class='ABC'][contains(@data-test-id,'ZZZ')]
Be careful with contains()
as its substring testing can yield false positives: ZZZ
is also a substring of ZZZZ
, for example. This more elaborate test can avoid the problem for delimited values such as you have with |
:
//a[@class='ABC'][contains(concat('|',@data-test-id,'|'), '|ZZZ|')]
Upvotes: 2
Reputation: 33384
Use either Following Xpath Or css selector.
Xpath:
//a[@class='ABC' and contains(@data-test-id,'ZZZ')]
Css Selector:
a.ABC[data-test-id*='ZZZ']
Upvotes: 2