2

There is an anchor tag, whose value can be changed by the user. Now, i want to write an Xpath query that searches for multiple link text names in one statement itself.

<a href="#login" class="fancybox" xpath="1">Signin</a>

now, link text value can be changed by user profile. for eg, "Login", "Log-in", "Click here to login" or "Login now"

If i write xpath:-

//a[contains(text(),'Login') or contains(text(),'Log-in') or contains(text(),'Login now') or contains(text(),'click here to Login')]

Then it fails. I need to click this element using Selenium.

Please help.

nick
  • 51
  • 5
  • Can you try it like this : By. Xpath(//a[@class='fancybox']) Then click on this element. – Nikita Bakshi Oct 23 '20 at 12:06
  • Your code looks fine. I don't know what the problem is, but your XPath expression looks perfectly OK. I wouldn't write it that way (for example, if the text contains 'Login now' then it also contains 'Login', so one of the conditions is redundant); but that doesn't explain it failing. – Michael Kay Oct 23 '20 at 13:45

2 Answers2

5

Important notes:

XPath 1.0

If you're certain there are no whitespace variations:

//a[.='Login' or .='Log-in' or .='Click here to login' or .='Login now']

Otherwise:

//a[   normalize-space()='Login" 
    or normalize-space()='Log-in' 
    or normalize-space()='Click here to login' 
    or normalize-space()='Login now']

XPath 2.0

//a[normalize-space()=('Login','Log-in','Click here to login','Login now')]
kjhughes
  • 89,675
  • 16
  • 141
  • 199
  • Hi, kjhughes, thanks for a detailed answer. I didnt knew that we can use comma separated values in OR conditions of XPath. So, is there any limit with the number of "OR" , "AND" that can be used in an XPath Expression. Like can i write 10-15 or more conditions for "OR"? – nick Oct 23 '20 at 18:04
  • Note that the `x=('a','b','c')` construct requires XPath 2.0 or higher. Regarding the maximum number of operands to `or` or `and`, there is no theoretical limit . There may be a limit for any given implementation, but 10-15 should be fine. – kjhughes Oct 23 '20 at 18:14
1

XPath is based on sequences. So you can use a comma separated list, i.e. sequence, to imitate logical OR conditions.

XPath

//a[text()=("Login","Log-in","Click here to login")]
Yitzhak Khabinsky
  • 8,935
  • 1
  • 11
  • 17
  • The OP is using Selenium, so he's stuck with the antiquated XPath 1.0 syntax. This construct requires XPath 2.0 or later. – Michael Kay Oct 23 '20 at 13:42