Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in XPATH to find an element by attribute value, not by name?

Tags:

xpath

For example I have an XML element:

<input id="optSmsCode" type="tel" name="otp" placeholder="SMS-code">

Suppose I know that somewhere there must be an attribute with otp value, but I don’t know in what attribute it can be, respectively, is it possible to have an XPath expression of type like this:

.//input[(contains(*, "otp")) or (contains(*, "ode"))]
like image 387
Ivan Yakushenko Avatar asked Oct 31 '25 11:10

Ivan Yakushenko


1 Answers

Try it like this and see if it works:

one = '//input/@*[(contains(.,"otp") or contains(.,"ode"))]/..'
print(driver.find_elements_by_xpath(one))

Edit:

The contains() function has a required cardinality of first argument of either one or zero. In plain(ish) English, it means you can check only one element at a time to see if it contains the target string.

So, the expression above goes through each attribute of input separately (/@*), checks if the attribute value of that specific attribute contains within it the target string and - if target is found - goes up to the parent of that attribute (/..) which, in the case of an attribute, is the node itself (input).

like image 151
Jack Fleeting Avatar answered Nov 02 '25 23:11

Jack Fleeting