Thursday, September 12, 2019

Post#17.Locators Part-3 (XPath)


XPath in Selenium WebDriver: Complete Tutorial
In Selenium automation, if the elements are not found by the general locators like id, class, name, etc. then XPath is used to find an element on the web page.

What is XPath?

XPath is defined as XML path. It is a syntax or language for finding any element on the web page using XML path expression.
XPath is used to find the location of any element on a webpage using HTML DOM structure.
Syntax for XPath: Xpath=//tagname[@attribute='value']
·       // : Select current node.
·       Tagname: Tagname of the particular node.
·       @: Select attribute.
·       Attribute: Attribute name of the node.
·       Value: Value of the attribute.

Types of X-path

There are two types of XPath:
1) Absolute XPath .
2) Relative XPath .
Absolute XPath :
It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.
The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.
Absolute xpath:
html/body/div[1]/table/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr/td[2]/a


Relative xpath:
For Relative Xpath the path starts from the middle of the HTML DOM structure. It starts with the double forward slash (//), which means it can search the element anywhere at the webpage.
You can starts from the middle of the HTML DOM structure and no need to write long xpath.
Below is the example of a relative XPath expression of the same element shown in the below screen. This is the common format used to find element through a relative XPath.

1)      Basic XPath:

XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, href,  etc. from the XML document as illustrated below.
Xpath=//input[@name='uname']

Here is a link to access the page : http://www.testingbar.com/loginpage/


Some more basic xpath expressions:
Xpath=//input[@type='text']                                            
Xpath= //label[@id='testing23']
Xpath= //input[@value='bar123']
Xpath=//*[@class='cancelbtn']
Xpath=//a[@href='http://testingbar.com/']
Xpath= //img[@src='//testingbar.com/images/LoginPage/mylogin.png']


2) Contains() :

Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically, for example, login information.

The contain feature has an ability to find the element with partial text as shown in below example.

In this example, we tried to identify the element by just using partial text value of the attribute. In the below XPath expression partial value 'sub' is used in place of submit button. It can be observed that the element is found successfully.
Complete value of 'Type' is 'submit' but using only partial value 'sub'.
Xpath=//*[contains(@type,'sub')]

Complete value of 'name' is 'LoginBtn' but using only partial value 'Btn'.
Xpath=//*[contains(@name,'Btn')]
In the above expression, we have taken the 'name' as an attribute and 'btn' as an partial value as shown in the below screenshot.




Similarly, in the below expression, we have taken the 'id' as an attribute and 'name' as a partial value. This will find 2 elements ('First Name’ & 'Last Name’) as its 'id' attribute contains 'name'.



Here is a link to access the page: http://www.testingbar.com/contact-form/




In the below expression, we have taken the "text" as an attribute and 'First' as a partial value as shown in the below screenshot. This will find the text ('First Name') as it displays the text 'First'.
Xpath //*[contains(text(),'First')]        




In the below expression, we have taken the "href" of the link as an attribute and ''google.com” as a partial value as shown in the below screenshot. This will find the Link (‘Visit Google Search Page ') as it displays the text 'google.com'.
Here is a link to access the page: http://www.testingbar.com/link-text/
Xpath=//*[contains(@href,'google.com')]




3) Using OR & AND:
In OR expression, two conditions are used, whether 1st condition OR 2nd condition should be true. It is also applicable if any one condition is true or maybe both. Means any one condition should be true to find the element.
In the below XPath expression, it identifies the elements whose single or both conditions are true.
Here is a link to access the page: http://www.testingbar.com/loginpage/
Xpath=//*[@type='submit' OR @name='ResetBtn']
Highlighting all elements having attribute 'type' as “submit” OR "name" as  “ResetBtn”.




In AND expression, two conditions are used, both conditions should be true to find the element. It fails to find element if any one condition is false.
Xpath //*[@type='submit' AND @name='LoginBtn']
In below expression, highlighting 'LOGIN' element as it having both attribute 'type' and 'name'.



4) Start-with functionStart-with function finds the element whose attribute value changes on refresh or any operation on the webpage. In this expression, match the starting text of the attribute is used to find the element whose attribute changes dynamically. You can also find the element whose attribute value is static (not changes).
For example -: Suppose the ID of particular element changes dynamically like:
Id=" userid12"
Id=" userid 345"
Id=" userid 8769"
And so on...

But the initial text is same. In this case, we use Start-with expression.

In the below expression, there are two elements with an id starting "testingbar "(i.e., 'UserName & 'Password' Field). In below example, XPath finds those element whose 'ID' starting with ' testingbar '.
Xpath //*[starts-with(@id,'testingbar')]



5) Text(): In this expression, with text function, we find the element with exact text match as shown below. In our case, we find the element with text "Username".
Xpath=//td[text()='Username']





Wild card Character with Xpath

-is the one of most used wild card character with xpath in selenium webdriver, we can use it instead of tag name and attribute

//* - matches all the elements present in the html (including html)

//div/* - matches all the immediate element(s) inside the div tag

//input[@*] - matches all the element(s) with input tag and have at least one attribute, attribute value may or may not present

//*[@*] - matches all the element(s) which have at least one attribute.

Position function in Xpath

Position function help the user to get the match at particular index, using position we can get element which are less than the position or greater than the position as well.
position function ://xpath[position()=2]
                                ://xpath[position()<2]
                                ://xpath[position()>2]
                                ://xpath[position()=<2]]  ...
Example : //button[position()=2]




Attribute value's Length xpath

We can find the element based on the attribute value/text length in selenium, string-length() method helps us to form the xpath based on the element's attribute length.
Syntax :// tagname[string-length(@attibute's name/text)= expectedLength]

tagname - is the html tag used to for the element like label,a, span, div..

@attibute's name - any attribute present in the element like id, name, src, href... text() - text() value present in the element.



expectedLength - numeric expected length of the attribute value or text value
Html code : <label id="twinkie" name='p'>selenium</label>
Xpath ://label[string-length(@id) = 7]
Xpath ://label[string-length(text()) = 8]
twinkie - 7 letters
selenium - 8 letters
Relational value Xpath
We can form xpath based on the numeric attribute value / text present in the element with relational operators. For example we can find the elements which have numeric text greater than 40 or less than 70 like so
Syntax :// tagname[@atrribute/function > expectedValue]
@atrribute/function - should result in numeric value
expectedValue - Must be numeric value
Html code : <label id="50" name='p'>30</label>
Xpath 1 ://label[text()>20]
Xpath 2 ://label[@id()<70]
Xpath 3 ://label[@id()<70][text()>20]

Axes in Xpath

XPath axes are used to identify elements which periodically change or refreshes it attributes by their relationship like parent, child, sibling, based on the independent element, whose properties does not change.
Axes refer to node on which elements are lying relative to an independent element. We could traverse in both forward and reverse directions.
Forward Axis : 

  • self
  • attribute
  • child
  • descendant
  • descendant-or-self
  • following-sibling
  • following

Reverse Axis : 
  • parent
  • ancestor
  • preceding-sibling
  • preceding
  • ancestor-or-self
Save below code as html file
<html>
              <head></head>
              <body>
                             <div name='username'>
                                           <label id="user">Username</label>
                                           <input id="username" type="text">
                             </div>
                             <div name='password'>
                                           <label id="pass">Password</label>
                                           <input id="username" type="password">
                             </div>
              </body>
</html>

Forward Axes

Forward axis in xpath helps to find the element/node after the current or reference element (helps to find element in the code which is below the current element in html file).

We can narrow down the matches by adding more details about the html element like tagnames, attributes.

self : It specifies the current element.

attribute : It specifies the attributes of the current element.
Now let's narrow down to the element(s), which have attribute id.
child : It specifies all child elements of the current element.


We can match the element with particular tag or ids, below one matches the child element(s) which have input as tag.


There are 5 "span" nodes matching by using "child" axis. If you want to focus on any particular element then you can use the below xpath:
Xpath= //*[@class='vertical-menu']/child::span[1]
You can change the xpath according to the requirement by putting [1], [2]…………and so on.
descendant : It specifies all the children and grand children elements.


Narrow down to the descendent which has input as tag.



descendant-or-self : It specifies current or all the children and grand children elements

Narrow down to the child which has input as tag, if the current element has input tag then this xpath matches that as well.

following-sibling : It specifies the following siblings of the current element. Siblings are at the same level as the current element and share its parent.



following : It specifies all elements that come after the current element which includes elements of other div's as well.



Reverse Axes
Reverse axis in xpath helps to find the element/node before the current or reference element (helps to find element in the code which is above the current element in html file)

We can narrow down the matches by adding more details about the html element like tagnames, attributes

parent : It specifies the parent of the current element.




ancestor : It specifies the ancestors of the current element/nodes which include the parents up to the root html.

Narrow the matches to the element(s) which has div as html tag by navigating to ancestors.

ancestor-or-self : It specifies current element or all elements that come before the current element.
Let's narrow down our search to the element which has tag as body from current element by navigating reverse axis, if current element is body then it matches with current element itself.

preceding-sibling : It specifies element that come before the current element.


No comments:

Post a Comment