Thursday, 28 April 2016

Web locators

This article talks about different locators used to find Web elements in browser and Mobile apps.

Different locators available in Selenium:-

id > name > class > link text > partial link text > tag name >  DOM(Selenium1) > css > xpath

Differences between XPath and CSS:-

XPath - we can search elements backward or forward in the DOM hierarchy

CSS - we can search elements only in a forward direction. 
This means that with XPath we can locate a parent element using a child element and visa versa.

Absolute xpath and relative xpath:-


Absolute xpath:- is the full path starting from root node and ends with desired descendant element node. starts with "/"
Ex:/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[1]/div[2]/form/table/tbody/tr[1]/td/input

Relative xpath:- doesn't start with root node, starts with "//"


Ex: //input[@id='Resultbox']

functions supported by CSS :-


Syntax Example Description
-------------------------------------------------------------------------------------
^= input[id^='ctrl'] Stars with: For example, if the ID of an element is ctrl_12, this will locate and return elements with ctrl at the beginning of the ID.

$= input[id$='_userName'] Ends with: For example, if the ID for an element is a_1_ userName, this will locate and return elements with _userName at the end of the ID.



*= Input[id*='userName'] Contains: For example, if the ID of an element is panel_ login_userName_textfield, this will use the userName part in the middle to match and locate the element.

functions supported by Xpath :-


Syntax Example Description
-------------------------------------------------------------------------------------
startswith():- Starting with: For example, if the ID of an element is ctrl_12, this will locate and return elements with ctrl at the beginning of the ID.
Ex: //input[starts-with(@id,'ctrl')]

contains():- Containing: For example, if the ID for an element is panel_login_userName_textfield, this will use the userName part in the middle to match and locate the element.

  Ex: Input[contains(@id,'userName')]

ancestor:- Selects all ancestors (parent, grandparent, and so on) of the current node.

Ex: //td[text()='Product 1']/ancestor::table

following:- Selects everything in the document after the closing tag of the current node.

Ex: //td[text()='Product 1']/following::tr

following-sibling:- Selects all siblings after the current node. 

Ex: //td[text()='product 1']/following-sibling:: td

preceding:- Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes, and namespace nodes.

Ex: //td[text()='$150']/preceding::tr

preceding-sibling:- Selects all siblings before the current node. 


Ex: //td[text()='$150']/preceding-sibling::td