Locators in Selenium
Locators in Selenium
Selenium
BY SAURABH DHINGRA
Locators in Selenium
1. Id
2. Name
3. Classname
4. Tagname
5. Linktext
6. Partial Linktext
7. Xpath
8. Css Selectors
XPath Definition
XPath is the path written using html
tags(or XML tags) and their attributes to
reach to a particular node (or web
element) in an HTML page or XML page.
Types of XPath:
Absolute XPath
Relative XPath
Absolute XPath
Absolute XPath starts from the beginning
of the page. As in an html page, the first
tag is HTML. So all absolute XPath always
start with html tag and then accessing
immediate child to reach to a node.
“/” is used to access an immediate child of
the parent tag.
Example:
html/body/table/tbody/tr[2]/td/input
Relative XPath
Relative XPath starts from anywhere on the
page.
“//” is used to access any child of the
parent tag.
Basic
Syntax: //htmlTagname[@attribute=’value’]
Example: //input[@type=’text’] –
It represents xpath of a WebElement which
is represented by an input tag and also has
an attribute type = ‘text’.
Absolute Vs Relative
Absolute xpath are fast, but they have one
disadvantage that if there is an addition or
deletion of some nodes in between, then
they fail to work.
In such a situation relative xpath are much
better, and one should be good at writing
dynamic xpath. There are some methods,
operators, and axes which are available in
xpath which can help to locate elements
uniquely.
How to Identify
Dynamic Web
Elements?
Dynamic Web Elements are one which
changes dynamically like – their attributes
such as Id or Classname are changing, or
text associated is changing.
Best possible way to identify these elements
is to first search for another web element
which stable and also can be identified
uniquely, then on this element using
methods, operators, or axes, one can reach
to the desired element.
Methods in XPaths:
Contains():
Contains is a method used when the value of
any attribute changes dynamically. It can search
an element with partial information.
Starts-with()–
This method can be used when we are
searching for web elements matching the start
of the text of the attributes passed. The text()
method can also be used which will match the
starting of the text.
Text() –
This method is used when we are searching for
elements matching the exact text.
Operators in XPath:
AND and OR are two operators available in
xpath.