XPath selects the second element from many, if only one does not exist

I have a webpage with three elements <input>that have the same attribute name. Ideally, I would like to select the second of these elements, except that there is only one element on the page, and I want to select this element instead.

Ideally, I would like something like (pseudocode, since it maxdoes not exist)

(//input[@name='myname'])[max(1, last()-1)]

I thought that maybe I could do something like the following, except that it gives all three elements

(//input[@name='myname'])[last()-1 or 1]

What is the best way to accomplish this using XPath?

+4
source share
1 answer

Perhaps take both the last only.

, . , .

((//input[@name='myname'])[position()=1 or position()=2])[last()]
+2

Source: https://habr.com/ru/post/1680439/


All Articles