Selenium Locators
Selenium Locators
com/in/anshulagarwal30
1.By.id
● Usage:driver.findElement(By.id("elementId"));
● Description: Locates an element using the value ofits id attribute.
● Advantages:
o Uniqueness: The id attribute should be unique on anHTML page.
o P
erformance: Fastest locator because browsers areoptimized for finding
elements by id.
● Limitations:
o Availability: Not all elements have an id attribute.
o D
ynamic IDs: Some web applications generate dynamicIDs that change on
each page load.
● Best Use Case: When the element has a unique and stableid attribute.
2.By.name
● Usage:driver.findElement(By.name("elementName"));
● Description: Locates an element using the value ofits name attribute.
● Advantages:
o Simplicity: Easy to use when the name attribute isunique.
● Limitations:
o Non-Uniqueness: The name attribute is not requiredto be unique.
● Best Use Case: When id is unavailable but the name attribute is unique and stable.
3.By.className
● Usage:driver.findElement(By.className("className"));
https://www.linkedin.com/in/anshulagarwal30
4.By.tagName
● Usage:driver.findElement(By.tagName("tagName"));
● Description: Locates elements by their HTML tag (e.g.,div, input).
● Advantages:
o Broad Selection: Can find all elements of a specifictype.
● Limitations:
o O
verly Broad: Often returns multiple elements; notsuitable for
unique identification.
● B
est Use Case: When dealing with lists or tables whereyou need to interact
with multiple elements of the same type.
5.By.linkText
● Usage:driver.findElement(By.linkText("exact link text"));
● Description: Locates anchor (<a>) elements by theirexact visible text.
● Advantages:
o Readability: Easy to understand and maintain.
● Limitations:
o Exact Match Required: The link text must match exactly,including whitespace.
o Case Sensitivity: Usually case-sensitive.
https://www.linkedin.com/in/anshulagarwal30
● Best Use Case: When you know the exact text of a linkand it is unique on the page.
6.By.partialLinkText
● Usage:driver.findElement(By.partialLinkText("partial link text"));
● Description: Locates anchor elements that containthe specified text.
● Advantages:
o Flexibility: Useful when only part of the link textis known.
● Limitations:
o Non-Uniqueness: May match multiple links if the partialtext is common.
o Performance: Slightly slower due to partial matching.
● Best Use Case: When the exact link text is dynamicbut contains a consistent substring.
7.By.cssSelector
● Usage:driver.findElement(By.cssSelector("cssSelector"));
● D
escription: Locates elements using CSS selectors,which define patterns to
select elements.
● Advantages:
o P
owerful: Can locate elements based on a variety ofattributes and
their combinations.
o Performance: Generally faster than XPath.
● Limitations:
o Complexity: Syntax can become complex for advancedselectors.
o Cannot Traverse Upwards: CSS selectors can't selectparent elements.
● B
est Use Case: When you need a flexible and efficientway to locate elements, especially
when id and name are not available.
8.By.xpath
● Usage:driver.findElement(By.xpath("xpathExpression"));
https://www.linkedin.com/in/anshulagarwal30
● D
escription: Locates elements using XPath expressions,a language for navigating XML
documents.
● Advantages:
o Flexibility: Can navigate both up and down the DOMtree.
o Rich Functions: Supports a variety of functions andaxes for complex selections.
● Limitations:
o Performance: Generally slower than other locators.
o Complexity: XPath syntax can be difficult to readand maintain.
o Browser Variations: Some older browsers have inconsistentXPath support.
● B
est Use Case: When no other locator can uniquelyidentify an element, or when you
need to traverse the DOM in complex ways.
Best Practices:
● Use IDs When Possible: Always check if the elementhas a unique id.
● Prefer CSS Selectors Over XPath: CSS selectors arefaster and more readable.
● A
void Hardcoding Text: Using By.linkText or By.partialLinkTextcan be brittle if the
text changes.
● H
andle Dynamic Elements: Be cautious with dynamicIDs or classes; consider
using stable attributes or relative locators.
● U
se Descriptive Locators: If possible, work with developersto add data-* attributes
specifically for testing.
● V
alidate Locators: Regularly verify that your locatorsare still valid as the application
evolves.
Examples:
● Using By.id:
WebElement usernameField = driver.findElement(By.id("username"));
● Using By.cssSelector:
// Locate an element with class 'btn' inside a div with id 'container'
WebElement button = driver.findElement(By.cssSelector("#container .btn"));
● Using By.xpath:
// Locate the third child div of an element with id 'main'
WebElement thirdDiv = driver.findElement(By.xpath("//div[@id='main']/div[3]"));
https://www.linkedin.com/in/anshulagarwal30
hoosing the right locator strategy is crucial for building robust and efficient UI automation
C
scripts. While By.id is generally the most preferable due to its uniqueness and speed,
real-world scenarios often require a mix of locator strategies. Understanding the pros and cons
of each helps in selecting the most appropriate one for each element.
Remember: Always aim for locators that are:
● Unique: They uniquely identify a single element.
● Stable: They do not change with UI updates.
● Efficient: They do not degrade the performance ofyour tests.
● Maintainable: They are easy to read and update.
y adhering to these principles, you'll enhance the reliability and longevity of your automation
B
suites.
● C
SS Selector: CSS Selector can only navigatedownwardin the DOM (i.e., from parent to
child), meaning it cannot select parent elements.
o Example (downward traversal):div #childElement
ifference: XPath allows you to select parent, sibling,or child elements, making it more flexible
D
for complex relationships. CSS Selector can only traverse downwards, so it is less flexible in
complex DOM hierarchies.
3.Performance
● X
Path: XPath is typicallyslowerthan CSS Selector,especially in browsers like Chrome
and Firefox, because it has to traverse the DOM in more complex ways.
● C
SS Selector: CSS Selector is generallyfasterbecausebrowsers are optimized for parsing
CSS, making it more efficient for locating elements.
Difference: CSS Selector is faster, while XPath isslower, especially in large DOMs.
4.Cross-Browser Compatibility
● X
Path: XPath isnot fully supported in Internet Explorer.It can cause issues or require
workarounds.
● C
SS Selector: CSS Selector worksconsistently acrossall modern browsers, including
Internet Explorer.
ifference: CSS Selectors have better cross-browsersupport compared to XPath, especially for
D
older browsers like IE.
5.Text Matching
● X
Path: XPath canfind elements by their text content,which is useful when you need to
locate elements based on visible text.
o Example://a[text()='Login']
● C
SS Selector: CSS Selectorcannot locate elementsby text content. You can only use
attribute selectors or class names.
o Example: Not available in CSS selectors.
ifference: XPath has the advantage of locating elementsbased on text content, which is
D
impossible in CSS Selectors.
https://www.linkedin.com/in/anshulagarwal30
7.Attribute Handling
● X
Path: XPath can select elements based onany attribute,even ones that
are dynamically generated or rarely used.
o Example://*[@data-test='testValue']
● C
SS Selector: CSS Selector can also target elementsbased onany attribute, though
certain complex attribute logic (like functions in XPath) may not be supported.
o Example:[data-test='testValue']
ifference: Both XPath and CSS Selectors handle attributeswell, but XPath offers more
D
flexibility with its ability to use functions like contains().
8.Selecting Siblings
● XPath: XPath allows you to selectpreceding and followingsiblingseasily.
o Example (following sibling)://h3[@id='heading']/following-sibling::p
● C
SS Selector: CSS Selector can only selectimmediatefollowing siblingsusing the +
selector or all following siblings using the ~ selector.
o Example (immediate sibling): h3 + p
o Example (all siblings): h3 ~ p
ifference: XPath is more flexible in selecting siblings,while CSS Selector is limited to selecting
D
the next sibling.
https://www.linkedin.com/in/anshulagarwal30
9.Positional Indexing
● X
Path: XPath allows you to find elements by theirexact positionin the DOM
using indices.
o Example://div[@class='example'][2](second div with class example)
● C
SS Selector: CSS Selector also supportsnth-childornth-of-typeto locate elements
based on their position in the DOM.
o Example:div.example:nth-child(2)
ifference: Both XPath and CSS Selector support positionalindexing, but XPath provides more
D
flexible options (e.g., last()).
● X
Pathis more powerful and flexible, especially forcomplex DOM traversals, text-based
element location, and handling dynamic elements.
● C
SS Selectoris faster, simpler, and more readable,making it ideal for most basic
to moderately complex scenarios.
F or most use cases in UI automation,CSS Selectoris preferable due to its speed and simplicity,
butXPathis indispensable when dealing with complexDOM structures or selecting elements
based on text.
Functions present in Xpath :
Path in Selenium provides a set of powerful functions that allow for flexible element
X
identification and manipulation. These functions can be categorized based on their use cases,
such as locating elements based on text, attributes, or relationships with other elements. Here’s
a breakdown of the most common functions in XPath used in Selenium, along with their
explanations:
1.contains()
● Syntax://*[contains(@attribute, 'value')]
● D
escription: This function is used to locate elementswhose attribute value contains
a specified substring.
● U
se Case: Useful when you only know part of an attributevalue and it might
be dynamic.
o E xample://input[contains(@id, 'login')]will find any <input> elements where
the id contains the substring "login."
2.starts-with()
● Syntax://*[starts-with(@attribute, 'value')]
● D
escription: This function selects elements whoseattribute value begins with a
specified substring.
● U
se Case: Helpful when the start of an attribute isconsistent, but the rest of the
value might be dynamic.
o E xample://div[starts-with(@class, 'header')]will select all div elements where
the class starts with "header."
https://www.linkedin.com/in/anshulagarwal30
3.text()
● Syntax://*[text()='textValue']
● Description: Locates elements that match the exactvisible text.
● Use Case: Used when you need to find elements basedon their visible text.
o E xample://a[text()='Login']will find an anchor (<a>) element with the exact
text "Login."
4.normalize-space()
● Syntax://*[normalize-space(text())='textValue']
● D
escription: This function removes leading and trailingwhitespace from a string
and collapses multiple spaces into a single space.
● Use Case: Useful when the text contains extra or irregularspacing.
o E xample://span[normalize-space(text())='Submit']will find the element with the
exact text "Submit" even if it has extra spaces.
5.last()
● Syntax:(//element)[last()]
● Description: Selects the last element in a set ofmatching nodes.
● Use Case: When you need to select the last elementin a group.
o Example:(//div)[last()]will find the last <div> on the page.
6.position()
● Syntax:(//element)[position()=n]
● Description: This function returns elements at a specificposition in a node set.
● U
se Case: Useful for selecting elements based on theirposition in a set of
similar elements.
o E xample:(//input)[position()=3]will select the third <input> element in
the document.
7.count()
● Syntax:count(//element)
● Description: Counts the number of elements that matchthe given XPath expression.
● Use Case: Helpful for verifying the number of occurrencesof a certain type of element.
https://www.linkedin.com/in/anshulagarwal30
● Syntax://element/preceding-sibling::siblingElement
● Description: Selects all sibling elements that precedethe current element.
● Use Case: Used to locate elements that come beforea given element.
o E xample://h1/preceding-sibling::pwill select all <p> elements that are siblings
preceding an <h1> element.
18.self::
● Syntax://element/self::element
● Description: Refers to the current node itself.
● U
se Case: Useful when you need to confirm that thecurrent node matches certain
criteria.
o E xample://div/self::div[@class='highlight']will select <div> elements that are
self and have a class of "highlight."
19.parent::
● Syntax://element/parent::parentElement
● Description: Selects the parent of a given element.
● Use Case: When you need to traverse upward and selectthe parent node.
o E xample://span[@class='child']/parent::divwill select the parent <div> of a
<span> element with the class "child."
20.preceding::
● Syntax://element/preceding::precedingElement
● Description: Selects all nodes that precede the currentnode in the document.
● U
se Case: When you want to locate any nodes that comebefore a given node in
the document.
o E xample://div[@id='main']/preceding::inputwill find all <input> elements that
precede the <div> with id="main".
Path functions in Selenium provide a powerful and flexible way to locate elements, especially
X
in complex or dynamic DOM structures. Some key functions to remember are:
● Text Matching: contains(), starts-with(), text()
https://www.linkedin.com/in/anshulagarwal30
Traversal in Xpath:
Path traversal is the process of navigating through the Document Object Model (DOM)
X
structure of a web page to locate elements based on their relationships to other elements, such
as parents, children, siblings, or ancestors. In Selenium, XPath traversal helps in identifying
elements when they cannot be found using simpler locators like id, name, or className. XPath
traversal uses axes such as parent, child, ancestor, descendant, sibling, and more.
WebElement parentElement =
driver.findElement(By.xpath("//input[@id='username']/parent::div"));
● E xplanation: This XPath expression selects the parent<div> of the <input> element
with id="username".
L ist<WebElement> childSpans =
driver.findElements(By.xpath("//div[@id='container']/child::span"));
● E xplanation: This XPath expression selects all <span>elements that are children of the
<div> with id="container".
● E xplanation: This XPath expression selects all <div>elements that are ancestors of the
<input> element with id="email".
List<WebElement> followingElements =
driver.findElements(By.xpath("//div[@class='header']/following::*"));
● E xplanation: This XPath expression selects all elementsthat appear after the <div>
with class "header" in the DOM, regardless of their structure or relation.
List<WebElement> precedingElements =
driver.findElements(By.xpath("//div[@class='content']/preceding::*"));
● E xplanation: This XPath expression selects all elementsthat appear before the <div>
with class "content" in the DOM.
Key Takeaways:
● Parent (parent::): Selects the immediate parent ofan element.
● Child (child::): Selects the immediate children ofan element.
● Ancestor (ancestor::): Selects all ancestor elements(parent, grandparent, etc.).
● Descendant (descendant::): Selects all descendants(children, grandchildren, etc.).
● F ollowing-sibling (following-sibling::): Selects siblingsthat appear after the current
element.
https://www.linkedin.com/in/anshulagarwal30
● P
receding-sibling (preceding-sibling::): Selects siblingsthat appear before the current
element.
● Following (following::): Selects all elements thatcome after the current element.
● Preceding (preceding::): Selects all elements thatcome before the current element.
● Self (self::): Refers to the current node itself.
Path traversal in Selenium is a powerful way to navigate through the DOM, allowing you to
X
select elements based on their hierarchical relationships. The flexibility of XPath traversal makes
it a valuable tool when simpler locators like id or name are insufficient. By mastering traversal
axes like ancestor::, descendant::, following-sibling::, and others, you can handle even the most
complex web structures in your automation scripts.
1.Parent Traversal (parent::)
Goal: Moveupwardsfrom the current element to itsparent.
● W
hat it does: If you have a child element (e.g., an<input> inside a <div>), this helps you
find the parent <div> of the <input> element.
Example:
HTML snippet:
<div class="form-group">
<input id="username" type="text" />
</div>
Step-by-step:
1. Identify the child element (<input id="username">).
2. Use the XPath to moveupto the parent <div>.
XPath Expression:
WebElement parentDiv = driver.findElement(By.xpath("//input[@id='username']/parent::div"));
Explanation:
● We are finding the <input> element by id="username".
https://www.linkedin.com/in/anshulagarwal30
<form id="loginForm">
<div class="form-group">
<input id="email" type="text" />
</div>
</form>
Step-by-step:
1. Identify the child element (<input id="email">).
2. Use the XPath to moveupto its ancestor <form>.
XPath Expression:
ebElement formElement =
W
driver.findElement(By.xpath("//input[@id='email']/ancestor::form"));
Explanation:
● We are finding the <input> with id="email".
● Then, we move up to its ancestor <form> element.
</div>
Step-by-step:
1. Identify the parent element (<div id="main">).
2. Use the XPath to movedownto all the <a> descendants.
XPath Expression:
L ist<WebElement> descendantLinks =
driver.findElements(By.xpath("//div[@id='main']/descendant::a"));
Explanation:
● We are finding the <div> with id="main".
● Then, we select all its descendant <a> elements, no matter how deeply they are nested.
Path traversal is about moving up, down, or sideways in the DOM to find elements based on
X
their relationships. Here's a quick summary:
y mastering these traversal techniques, we can handle even the most complex DOM structures
B
in Selenium testing!