As we know it is always better to use ID and Name to locate the elements which will work for sure. You don't need to search for any other locator if there is ID or Name present in your application.
Let us look for xpath examples to use ID and Name effectively with combinations
If the html looks like below :
<input type="text" aria-label="Email or Phone" value="Email or Phone" tabindex="1" placeholder="" name="email" id="email" class="inputtext _5aju" style="background-color: transparent;">
We can use as below :
In xpath we can use in different ways
1. With ID : - //input[@id='email'] or we can also use as //*[@id='email']
2. With Name - //input[@name='email'] or we can also use as //*[@name='email']
In css we can use as below :
1. With ID - css=input#email or css=#email
2. With Name - css=input[name=email] or css=[name=email]
All the above syntaxs are simple. We can directly use them by using id or name locators.
Here using xpath / Css, we can combine two locators when ever required, lets see how we can achve.
Using xpath : - //*[@id='email' or @name='email'], here first it will check for the id and then it will check for the second.
Based on index also, we can define the path.
We can also define by the using the value attribute
//input[@name='email'][@value='Email or Phone']
The same with Css css=input[name=email][value=Email or Phone]
We can also define xpath with 'Style' attribute.
xpath: //input[@name='email'][@style='background-color: transparent;']
Working with Text
Now lets us look at the examples for 'Text'. When working with text, we will have two scenarios, one is 'Exactly' and other
one is 'Contains'. As name describes, 'Exactly' willl try to find the exact match and Contains looks for multiple matches.
We can use like this //button[.='Log In'] as Xpath to findout element containing exactly 'Log In'.
IF the HTML is as below:
<div class="fwb fcb" style="background-color: transparent;">Sign Up</div>
We find element by using xpath as //div[contains(text(),'Sign up')] or //div[contains(text(),'Sign')]
The above can be done using css as.
Working with Links:
Links have anchor tags, we can apply the same as we applied for 'Text', the only difference here is we should add anchor tag.
We can just use as 'link=Forgot your password?', using xpath we should use as //a[.='Forgot your password?']
We can also specify the partial text of the link as //a[contains(text(),'Forgot')]. This also can be written as //a[contains(.,'Forgot')]. We replaced 'text()' with 'dot'.
In Css we rewrite them as css=a:contains('Forgot')
Some times we may need to work with URLs with href attributes. The below xpath can also be used instead of finding the link text.