Locators
Mastering Locators in Selenium
What Are Locators?
Locators are the search criteria used to identify web elements on a webpage. Selenium supports eight primary locator strategies:
- Id
- Name
- Class
- Link Text
- Partial Link Text
- Tag Name
- CSS Selector
- XPath
These strategies are implemented as methods in Selenium’s By
class, which provides static methods to define each locator.
Using findElement()
The findElement()
method in Selenium is used to locate a single web element based on the given locator strategy.
Example: driver.findElement(By.id("loginButton")).click();
Sample HTML Code with Duplicate Elements
<html> <head> <title>DemoSite</title> </head> <body> <div> <input type="text" id="abc"> <input type="text" id="abc"> </div> <div> <input type="text" id="abc"> <input type="text" id="abc"> </div> </body> </html>
CSS Selectors
CSS (Cascading Style Sheets) selectors are powerful and flexible for locating elements when IDs, names, and classes are not available or are duplicated.
Why Use CSS Selectors in Selenium?
- To identify elements without ID, name, or class attributes.
- To locate elements within a Shadow DOM.
- Faster compared to XPath.
Syntax
driver.findElement(By.cssSelector("input[title=\"Search\"]")).sendKeys("TestYantra");
Shortcuts for CSS Selectors
- ID Selector:
tagName#idValue
- Class Selector:
tagName.classValue
Drawbacks
- CSS Selectors do not support the
text()
function. - They cannot perform backward traversing.
XPath
XPath is a language for navigating through elements and attributes in an XML document. It's highly versatile and can be used when CSS Selectors are insufficient.
Types of XPath
- Absolute XPath: Starts from the root element.
- Relative XPath: Starts from the current element.
XPath Strategies
- By Attribute:
//tagname[@attributeName='attributeValue']
- By Text:
//tagname[text()='textValue']
- By Contains:
//tagname[contains(text(),'textValue')]
- Independent and Dependent XPath: Used for dynamic elements by traversing between fixed and dynamic elements.
- XPath Axes: Used to identify elements based on their relationship to other elements.
Advantages and Drawbacks
Advantages of CSS Selector
- Faster than XPath.
- Supports Shadow DOM elements.
- Supported by all browsers.
Drawbacks of CSS Selector
- Cannot identify elements by text.
- Does not support backward traversing.
Advantages of XPath
- Supports
text()
function. - Can perform both forward and backward traversing.
- Ideal for identifying dynamic and duplicate elements.
Drawbacks of XPath
- Slower compared to CSS Selector.
- More complex syntax.
Conclusion
Understanding and effectively using locators is fundamental for automation engineers. Each locator strategy has its strengths and weaknesses, making them suitable for different scenarios. By mastering locators, you can write more efficient, reliable, and maintainable Selenium scripts, paving the way for successful web automation projects.
Comments
Post a Comment