Selenium_Locators_Uses_Preferences
Selenium_Locators_Uses_Preferences
In Selenium WebDriver locators are used to find and interact with elements on a web page.
Selecting the right locator is crucial for creating reliable and maintainable automation scripts.
1. By.id
• Usage: driver.findElement(By.id("elementId"));
• Description: Locates an element using the value of its id attribute.
• Advantages:
o Uniqueness: The id attribute should be unique on an HTML page.
o Performance: Fastest locator because browsers are optimized for finding
elements by id.
• Limitations:
o Availability: Not all elements have an id attribute.
o Dynamic IDs: Some web applications generate dynamic IDs that change on each
page load.
• Best Use Case: When the element has a unique and stable id attribute.
2. By.name
• Usage: driver.findElement(By.name("elementName"));
• Description: Locates an element using the value of its name attribute.
• Advantages:
o Simplicity: Easy to use when the name attribute is unique.
• Limitations:
o Non-Uniqueness: The name attribute is not required to 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"));
• Description: Locates elements by the value of their class attribute.
• Advantages:
o Grouping: Useful for finding elements that share a common style.
• Limitations:
o Multiple Classes: If an element has multiple classes, this locator may not work as
expected.
o Non-Uniqueness: Classes are often shared among multiple elements.
• Best Use Case: When you need to find elements that have a unique class name.
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 specific type.
• Limitations:
o Overly Broad: Often returns multiple elements; not suitable for unique
identification.
• Best Use Case: When dealing with lists or tables where you 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 their exact 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.
• Best Use Case: When you know the exact text of a link and it is unique on the page.
6. By.partialLinkText
• Usage: driver.findElement(By.partialLinkText("partial link text"));
• Description: Locates anchor elements that contain the specified text.
• Advantages:
o Flexibility: Useful when only part of the link text is known.
• Limitations:
o Non-Uniqueness: May match multiple links if the partial text is common.
o Performance: Slightly slower due to partial matching.
• Best Use Case: When the exact link text is dynamic but contains a consistent substring.
7. By.cssSelector
• Usage: driver.findElement(By.cssSelector("cssSelector"));
• Description: Locates elements using CSS selectors, which define patterns to select
elements.
• Advantages:
o Powerful: Can locate elements based on a variety of attributes and their
combinations.
o Performance: Generally faster than XPath.
• Limitations:
o Complexity: Syntax can become complex for advanced selectors.
o Cannot Traverse Upwards: CSS selectors can't select parent elements.
• Best Use Case: When you need a flexible and efficient way to locate elements, especially
when id and name are not available.
8. By.xpath
• Usage: driver.findElement(By.xpath("xpathExpression"));
• Description: Locates elements using XPath expressions, a language for navigating XML
documents.
• Advantages:
o Flexibility: Can navigate both up and down the DOM tree.
o Rich Functions: Supports a variety of functions and axes for complex selections.
• Limitations:
o Performance: Generally slower than other locators.
o Complexity: XPath syntax can be difficult to read and maintain.
o Browser Variations: Some older browsers have inconsistent XPath support.
• Best Use Case: When no other locator can uniquely identify an element, or when you
need to traverse the DOM in complex ways.
Best Practices:
• Use IDs When Possible: Always check if the element has a unique id.
• Prefer CSS Selectors Over XPath: CSS selectors are faster and more readable.
• Avoid Hardcoding Text: Using By.linkText or By.partialLinkText can be brittle if the text
changes.
• Handle Dynamic Elements: Be cautious with dynamic IDs or classes; consider using
stable attributes or relative locators.
• Use Descriptive Locators: If possible, work with developers to add data-* attributes
specifically for testing.
• Validate Locators: Regularly verify that your locators are 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]"));
Choosing the right locator strategy is crucial for building robust and efficient UI automation
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 of your tests.
• Maintainable: They are easy to read and update.
By adhering to these principles, you'll enhance the reliability and longevity of your automation
suites.
The two most commonly used locators in Selenium—XPath and CSS Selector—have their own
strengths and limitations. Here's a detailed comparison of their key differences:
1. Syntax Complexity
• XPath: XPath syntax is more verbose and complex, especially when working with
dynamic or nested elements.
o Example: //div[@class='example']
• CSS Selector: CSS Selector has a cleaner and more compact syntax, making it easier to
read and write in many cases.
o Example: div.example
Difference: XPath can become more complex and harder to maintain, especially in complex
DOM hierarchies, while CSS selectors are generally simpler and easier to read.
3. Performance
• XPath: XPath is typically slower than CSS Selector, especially in browsers like Chrome
and Firefox, because it has to traverse the DOM in more complex ways.
• CSS Selector: CSS Selector is generally faster because browsers are optimized for parsing
CSS, making it more efficient for locating elements.
Difference: CSS Selector is faster, while XPath is slower, especially in large DOMs.
4. Cross-Browser Compatibility
• XPath: XPath is not fully supported in Internet Explorer. It can cause issues or require
workarounds.
• CSS Selector: CSS Selector works consistently across all modern browsers, including
Internet Explorer.
Difference: CSS Selectors have better cross-browser support compared to XPath, especially for
older browsers like IE.
5. Text Matching
• XPath: XPath can find elements by their text content, which is useful when you need to
locate elements based on visible text.
o Example: //a[text()='Login']
• CSS Selector: CSS Selector cannot locate elements by text content. You can only use
attribute selectors or class names.
o Example: Not available in CSS selectors.
Difference: XPath has the advantage of locating elements based on text content, which is
impossible in CSS Selectors.
6. Functions and Operators
• XPath: XPath supports various functions and operators, such as contains(), starts-with(),
and, or, which makes it more powerful for complex queries.
o Example: //input[contains(@name,'username')]
• CSS Selector: CSS Selector lacks advanced functions like contains(), though you can use
attribute selectors for partial matches (^=, *=).
o Example: input[name*='username']
Difference: XPath is more feature-rich with functions like contains() and starts-with(), making it
more powerful for specific matching scenarios.
7. Attribute Handling
• XPath: XPath can select elements based on any attribute, even ones that are
dynamically generated or rarely used.
o Example: //*[@data-test='testValue']
• CSS Selector: CSS Selector can also target elements based on any attribute, though
certain complex attribute logic (like functions in XPath) may not be supported.
o Example: [data-test='testValue']
Difference: Both XPath and CSS Selectors handle attributes well, but XPath offers more flexibility
with its ability to use functions like contains().
8. Selecting Siblings
• XPath: XPath allows you to select preceding and following siblings easily.
o Example (following sibling): //h3[@id='heading']/following-sibling::p
• CSS Selector: CSS Selector can only select immediate following siblings using the +
selector or all following siblings using the ~ selector.
o Example (immediate sibling): h3 + p
o Example (all siblings): h3 ~ p
Difference: XPath is more flexible in selecting siblings, while CSS Selector is limited to selecting
the next sibling.
9. Positional Indexing
• XPath: XPath allows you to find elements by their exact position in the DOM using
indices.
o Example: //div[@class='example'][2] (second div with class example)
• CSS Selector: CSS Selector also supports nth-child or nth-of-type to locate elements
based on their position in the DOM.
o Example: div.example:nth-child(2)
Difference: Both XPath and CSS Selector support positional indexing, but XPath provides more
flexible options (e.g., last()).
• XPath is more powerful and flexible, especially for complex DOM traversals, text-based
element location, and handling dynamic elements.
• CSS Selector is faster, simpler, and more readable, making it ideal for most basic to
moderately complex scenarios.
For most use cases in UI automation, CSS Selector is preferable due to its speed and simplicity,
but XPath is indispensable when dealing with complex DOM structures or selecting elements
based on text.
Functions present in Xpath :
XPath in Selenium provides a set of powerful functions that allow for flexible element
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')]
• Description: This function is used to locate elements whose attribute value contains a
specified substring.
• Use Case: Useful when you only know part of an attribute value and it might be
dynamic.
o Example: //input[contains(@id, 'login')] will find any <input> elements where the
id contains the substring "login."
2. starts-with()
• Syntax: //*[starts-with(@attribute, 'value')]
• Description: This function selects elements whose attribute value begins with a specified
substring.
• Use Case: Helpful when the start of an attribute is consistent, but the rest of the value
might be dynamic.
o Example: //div[starts-with(@class, 'header')] will select all div elements where
the class starts with "header."
3. text()
• Syntax: //*[text()='textValue']
• Description: Locates elements that match the exact visible text.
• Use Case: Used when you need to find elements based on their visible text.
o Example: //a[text()='Login'] will find an anchor (<a>) element with the exact text
"Login."
4. normalize-space()
• Syntax: //*[normalize-space(text())='textValue']
• Description: This function removes leading and trailing whitespace from a string and
collapses multiple spaces into a single space.
• Use Case: Useful when the text contains extra or irregular spacing.
o Example: //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 of matching nodes.
• Use Case: When you need to select the last element in 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 specific position in a node set.
• Use Case: Useful for selecting elements based on their position in a set of similar
elements.
o Example: (//input)[position()=3] will select the third <input> element in the
document.
7. count()
• Syntax: count(//element)
• Description: Counts the number of elements that match the given XPath expression.
• Use Case: Helpful for verifying the number of occurrences of a certain type of element.
o Example: count(//div) will return the number of <div> elements on the page.
8. substring()
• Syntax: substring(string, start, length)
• Description: Extracts a substring from the input string starting at the given position.
• Use Case: Used for selecting part of a string from an element or attribute value.
o Example: //div[substring(@id, 1, 3)='log'] will find any <div> element whose id
starts with "log."
9. substring-before()
• Syntax: substring-before(string1, string2)
• Description: Returns the part of the string before a given substring.
• Use Case: Useful when you want to extract the text before a certain character or string.
o Example: substring-before('login-form', '-') will return "login."
10. substring-after()
• Syntax: substring-after(string1, string2)
• Description: Returns the part of the string after a given substring.
• Use Case: Similar to substring-before(), but it extracts the part after the specified string.
o Example: substring-after('login-form', '-') will return "form."
11. not()
• Syntax: //element[not(@attribute)]
• Description: Selects elements that do not have a specified attribute or value.
• Use Case: Useful when filtering out elements that have a certain attribute.
o Example: //input[not(@type='submit')] will find all <input> elements that are not
of type "submit."
12. and
• Syntax: //element[@attribute1='value1' and @attribute2='value2']
• Description: Allows you to combine multiple conditions.
• Use Case: Use this when you want to combine multiple attribute conditions in a single
XPath query.
o Example: //input[@type='text' and @name='username'] will find an <input>
element where type is "text" and name is "username."
13. or
• Syntax: //element[@attribute1='value1' or @attribute2='value2']
• Description: Allows multiple conditions to be evaluated, returning elements that match
at least one condition.
• Use Case: Used when you want to match elements that meet at least one of the
specified conditions.
o Example: //input[@type='submit' or @type='button'] will find all <input>
elements that are either of type "submit" or "button."
14. ancestor::
• Syntax: //element/ancestor::ancestorElement
• Description: Selects all ancestor elements of a given element.
• Use Case: Useful for selecting parent or grandparent elements.
o Example: //span/ancestor::div will select all the <div> ancestors of a <span>
element.
15. descendant::
• Syntax: //element/descendant::descendantElement
• Description: Selects all descendants of a given element, including children and
grandchildren.
• Use Case: When you need to locate child elements at any depth.
o Example: //div[@id='main']/descendant::input will find all <input> elements
within the div with id="main".
16. following-sibling::
• Syntax: //element/following-sibling::siblingElement
• Description: Selects all sibling elements that follow the current element.
• Use Case: Used to locate elements that come immediately after a given element.
o Example: //h1/following-sibling::p will select all <p> elements that are siblings
following an <h1> element.
17. preceding-sibling::
• Syntax: //element/preceding-sibling::siblingElement
• Description: Selects all sibling elements that precede the current element.
• Use Case: Used to locate elements that come before a given element.
o Example: //h1/preceding-sibling::p will select all <p> elements that are siblings
preceding an <h1> element.
18. self::
• Syntax: //element/self::element
• Description: Refers to the current node itself.
• Use Case: Useful when you need to confirm that the current node matches certain
criteria.
o Example: //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 select the parent node.
o Example: //span[@class='child']/parent::div will 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 current node in the document.
• Use Case: When you want to locate any nodes that come before a given node in the
document.
o Example: //div[@id='main']/preceding::input will find all <input> elements that
precede the <div> with id="main".
XPath functions in Selenium provide a powerful and flexible way to locate elements, especially
in complex or dynamic DOM structures. Some key functions to remember are:
• Text Matching: contains(), starts-with(), text()
• Traversing the DOM: ancestor::, descendant::, parent::, following-sibling::
• Attribute Matching: contains(), starts-with(), not()
• Handling Positions: position(), last()
Choosing the right XPath function depends on the structure of the web page and how dynamic
the elements are. These functions allow you to handle a wide variety of scenarios, from simple
attribute matching to complex DOM traversals.
Traversal in Xpath:
XPath traversal is the process of navigating through the Document Object Model (DOM)
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.
Key Takeaways:
• Parent (parent::): Selects the immediate parent of an element.
• Child (child::): Selects the immediate children of an element.
• Ancestor (ancestor::): Selects all ancestor elements (parent, grandparent, etc.).
• Descendant (descendant::): Selects all descendants (children, grandchildren, etc.).
• Following-sibling (following-sibling::): Selects siblings that appear after the current
element.
• Preceding-sibling (preceding-sibling::): Selects siblings that appear before the current
element.
• Following (following::): Selects all elements that come after the current element.
• Preceding (preceding::): Selects all elements that come before the current element.
• Self (self::): Refers to the current node itself.
XPath traversal in Selenium is a powerful way to navigate through the DOM, allowing you to
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: Move upwards from the current element to its parent.
• What 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 move up to 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".
• Then, we move up to its parent element (<div>).
XPath traversal is about moving up, down, or sideways in the DOM to find elements based on
their relationships. Here's a quick summary:
By mastering these traversal techniques, we can handle even the most complex DOM structures
in Selenium testing!