Introduction to Locators

In Selenium WebDriver, a locator is a mechanism used to identify elements on a web page. Accurate and efficient locators are essential for interacting with web elements such as buttons, links, input fields, and images. Once an element is located, you can perform various actions like clicking, typing, or retrieving its attributes.

Throughout automation, there are two primary tasks:

  • Locating Web Elements: Identifying and finding elements on the web page.
  • Performing Actions: Executing operations on the located elements.

Mastering locators ensures that your automation scripts can reliably interact with web pages, even as the UI evolves.

Types of Locators

Selenium supports a variety of locators, categorized into Basic Locators and Customized Locators.

Basic Locators

Basic locators are straightforward and directly supported by Selenium’s By class. They rely on common HTML attributes to identify elements uniquely or within groups.

Customized Locators

When basic locators are insufficient—perhaps due to dynamic attributes or complex DOM structures—customized locators like XPath and CSS Selectors come into play. These allow for more flexible and powerful element identification strategies.

1. ID Locator

Definition: Locates an element by its unique id attribute.

Usage:

WebElement element = driver.findElement(By.id("uniqueElementId"));

Advantages:

  • Uniqueness: id attributes are intended to be unique within an HTML document.
  • Performance: Locating by id is typically faster than other locators.

Example:

// Locate the search box using ID and enter text
WebElement searchBox = driver.findElement(By.id("search-input"));
searchBox.sendKeys("Selenium WebDriver");

2. Name Locator

Definition: Locates elements by the name attribute.

Usage:

WebElement element = driver.findElement(By.name("elementName"));

Advantages:

  • Simplicity: Easy to use when name attributes are present and unique.
  • Forms: Commonly used in form elements like input fields.

Example:

// Locate the search box using Name and enter text
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Java Automation");

Definition: Locates anchor (<a>) elements by their visible text.

Usage:

WebElement link = driver.findElement(By.linkText("Click Here"));

Advantages:

  • Readability: Makes the code more readable by using the link’s visible text.
  • Specificity: Ideal when link texts are unique.

Example:

// Locate and click the 'Tablets' link using Link Text
WebElement tabletsLink = driver.findElement(By.linkText("Tablets"));
tabletsLink.click();

Definition: Locates anchor (<a>) elements that contain a specified substring in their visible text.

Usage:

WebElement link = driver.findElement(By.partialLinkText("Click"));

Advantages:

  • Flexibility: Useful when link texts are long or partially known.
  • Dynamic Texts: Handles scenarios where link texts may vary slightly.

Example:

// Locate and click the 'Tablet' link using Partial Link Text
WebElement tabletLink = driver.findElement(By.partialLinkText("Tab"));
tabletLink.click();

Caution:

  • Ambiguity: Partial texts may match multiple links, leading to unexpected behavior.
  • Best Practice: Prefer using full link text when possible to ensure uniqueness.

5. Class Name Locator

Definition: Locates elements by their class attribute.

Usage:

List<WebElement> elements = driver.findElements(By.className("commonClass"));

Advantages:

  • Grouping: Ideal for locating multiple elements sharing the same class.
  • Styling Hooks: Often used when elements are styled uniformly.

Example:

// Locate all header links using Class Name
List<WebElement> headerLinks = driver.findElements(By.className("header-link"));
System.out.println("Total Header Links: " + headerLinks.size());

6. Tag Name Locator

Definition: Locates elements by their tag name (e.g., a, img, div).

Usage:

List<WebElement> links = driver.findElements(By.tagName("a"));

Advantages:

  • Comprehensive: Captures all elements of a particular type.
  • Counting Elements: Useful for counting or iterating over groups of elements.

Example:

// Locate all links on the page using Tag Name
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Total Links on Page: " + allLinks.size());

Customized Locators

When basic locators are inadequate, customized locators provide the necessary flexibility to target elements based on more complex criteria.

1. XPath Locator

Definition: A powerful language for navigating XML documents, including HTML.

Usage:

WebElement element = driver.findElement(By.xpath("//tag[@attribute='value']"));

Advantages:

  • Flexibility: Can navigate complex DOM structures.
  • Advanced Selection: Supports conditions, indexing, and hierarchical relationships.

Example:

// Locate the search button using XPath
WebElement searchButton = driver.findElement(By.xpath("//button[@type='submit']"));
searchButton.click();

2. CSS Selector Locator

Definition: Utilizes CSS selectors to locate elements.

Usage:

WebElement element = driver.findElement(By.cssSelector("tag.class#id"));

Advantages:

  • Performance: Generally faster than XPath.
  • Familiarity: Leverages CSS syntax, which many developers are already familiar with.

Example:

// Locate the login button using CSS Selector
WebElement loginButton = driver.findElement(By.cssSelector("button.login-btn"));
loginButton.click();

Understanding findElement vs findElements

Selenium WebDriver provides two primary methods for locating elements:

  • findElement: Locates a single web element.
  • findElements: Locates a list of web elements.

Scenario 1: Locator Matches a Single Element

Description: The locator uniquely identifies one element on the page.

Usage:

WebElement element = driver.findElement(By.id("uniqueId"));
List<WebElement> elements = driver.findElements(By.id("uniqueId"));

Outcome:

  • findElement: Returns the single WebElement.
  • findElements: Returns a List containing one WebElement.

Example:

// Using findElement
WebElement searchBox = driver.findElement(By.id("search-input"));
// Using findElements
List<WebElement> searchBoxes = driver.findElements(By.id("search-input"));
System.out.println("Number of Search Boxes: " + searchBoxes.size());

Notes:

  • searchBoxes.size() would output 1.
  • Even though findElements returns a list, it contains only the matching element.

Scenario 2: Locator Matches Multiple Elements

Description: The locator matches more than one element on the page.

Usage:

WebElement firstElement = driver.findElement(By.className("commonClass"));
List<WebElement> elements = driver.findElements(By.className("commonClass"));

Outcome:

  • findElement: Returns the first WebElement in the DOM.
  • findElements: Returns a List of all matching WebElements.

Example:

// Using findElement
WebElement firstHeaderLink = driver.findElement(By.className("header-link"));
// Using findElements
List<WebElement> headerLinks = driver.findElements(By.className("header-link"));
System.out.println("Total Header Links: " + headerLinks.size());

Notes:

  • firstHeaderLink references the first element with the class header-link.
  • headerLinks.size() indicates how many elements share that class.

Scenario 3: Locator Matches No Elements

Description: The locator does not match any elements on the page.

Usage:

WebElement element = driver.findElement(By.id("nonExistentId"));
List<WebElement> elements = driver.findElements(By.id("nonExistentId"));

Outcome:

  • findElement: Throws a NoSuchElementException.
  • findElements: Returns an empty List.

Example:

try {
    // Using findElement with a non-existent ID
    WebElement missingElement = driver.findElement(By.id("missing-id"));
} catch (NoSuchElementException e) {
    System.out.println("Element not found!");
}
// Using findElements with a non-existent ID
List<WebElement> missingElements = driver.findElements(By.id("missing-id"));
System.out.println("Number of Missing Elements: " + missingElements.size());

Notes:

  • It’s good practice to handle exceptions when using findElement to avoid script termination.
  • findElements can be safely used to check for the presence of elements without exception handling.

Practical Examples

Let’s apply what we’ve learned with some hands-on examples.

Example 1: Using ID Locator

Objective: Locate the search box by its id and enter text.

Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class IDLocatorExample {
    public static void main(String[] args) {
        // Step 1: Launch Chrome Browser
        WebDriver driver = new ChromeDriver();

        // Step 2: Open the application URL
        driver.get("https://www.demo.opencart.com");

        // Step 3: Maximize the browser window
        driver.manage().window().maximize();

        // Step 4: Locate the search box using ID and enter text
        WebElement searchBox = driver.findElement(By.id("search"));
        searchBox.sendKeys("MacBook");

        // Optional: Close the browser
        driver.close();
    }
}

Explanation:

  • Launching Browser: Initializes ChromeDriver to control the Chrome browser.
  • Navigating to URL: Opens the specified OpenCart demo website.
  • Maximizing Window: Ensures the browser window is fully visible.
  • Locating Element: Finds the search input box using its id (search).
  • Performing Action: Enters “MacBook” into the search box.

Objective: Locate and click on the “Tablets” link using both Link Text and Partial Link Text.

Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class LinkTextExample {
    public static void main(String[] args) {
        // Step 1: Launch Chrome Browser
        WebDriver driver = new ChromeDriver();

        // Step 2: Open the application URL
        driver.get("https://www.demo.opencart.com");

        // Step 3: Maximize the browser window
        driver.manage().window().maximize();

        // Step 4: Locate and click the 'Tablets' link using Link Text
        WebElement tabletsLink = driver.findElement(By.linkText("Tablets"));
        tabletsLink.click();

        // Step 5: Navigate back to the homepage
        driver.navigate().back();

        // Step 6: Locate and click the 'Tablets' link using Partial Link Text
        WebElement tabletsPartialLink = driver.findElement(By.partialLinkText("Tab"));
        tabletsPartialLink.click();

        // Optional: Close the browser
        driver.close();
    }
}

Explanation:

  • Using Link Text: Accurately locates the “Tablets” link and clicks it.
  • Using Partial Link Text: Locates the link by a substring (“Tab”) and clicks it.

Caution:

  • Partial Link Text may match multiple elements if substrings overlap, leading to unexpected clicks.
  • Best Practice: Use full Link Text when possible to ensure the correct element is targeted.

Example 3: Using Class Name and Tag Name Locators

Objective: Locate all header links using Class Name and count the total number of links using Tag Name.

Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;

public class ClassNameAndTagNameExample {
    public static void main(String[] args) {
        // Step 1: Launch Chrome Browser
        WebDriver driver = new ChromeDriver();

        // Step 2: Open the application URL
        driver.get("https://www.demo.opencart.com");

        // Step 3: Maximize the browser window
        driver.manage().window().maximize();

        // Step 4: Locate all header links using Class Name
        List<WebElement> headerLinks = driver.findElements(By.className("header-link"));
        System.out.println("Total Header Links: " + headerLinks.size());

        // Optional: Iterate and print each header link text
        for (WebElement link : headerLinks) {
            System.out.println("Header Link Text: " + link.getText());
        }

        // Step 5: Locate all links on the page using Tag Name
        List<WebElement> allLinks = driver.findElements(By.tagName("a"));
        System.out.println("Total Links on Page: " + allLinks.size());

        // Optional: Close the browser
        driver.close();
    }
}

Explanation:

  • Using Class Name: Finds all elements with the class header-link and counts them.
  • Using Tag Name: Finds all <a> tags (links) on the page and counts them.

Notes:

  • Class Name Locator is ideal for grouping similar elements.
  • Tag Name Locator is useful for comprehensive element counts across the entire page.

Best Practices for Using Locators

  • Prefer Unique Locators: Always aim to use locators that uniquely identify elements, such as ID or unique name attributes.
  • Minimize Locator Dependency on UI Changes: Choose locators less likely to change with UI updates to enhance script stability.
  • Use Explicit Locators Before Customized Ones: Start with basic locators and resort to XPath or CSS Selectors when necessary.
  • Avoid Using Indexes in Locators: Index-based locators can become unreliable if the UI structure changes.
  • Leverage Browser DevTools: Utilize browser inspection tools to analyze and choose the most effective locators.
  • Maintain Consistency: Stick to a consistent locator strategy across your project for readability and maintainability.

Assignment

Objective: Apply your knowledge of locators by automating a series of tasks on the OpenCart demo website.

Tasks:

  1. Find Total Number of Links:
    • Locate all links on the homepage using the Tag Name locator.
    • Print the total number of links found.
  2. Find Total Number of Images:
    • Locate all images on the homepage using the Tag Name locator.
    • Print the total number of images found.
  3. Print Each Link’s Text:
    • Iterate through the list of links obtained.
    • Print the visible text of each link to the console.
  4. Click on a Product Link Using Link Text:
    • Locate a product link (e.g., “Desktops”) using the Link Text locator.
    • Click on the link to navigate to the product page.
  5. Verify Page Navigation:
    • After clicking the link, verify that the page title matches the expected title of the product page.
    • Print the result of the verification (Passed/Failed).
  6. Submission:
    • Create a new Java class (e.g., LocatorAssignment) in your Selenium project.
    • Implement the tasks with appropriate comments.
    • Run the script to ensure it performs as expected.
    • Optionally, share the script with peers or instructors for feedback.

Example Structure:

public class LocatorAssignment {
    public static void main(String[] args) {
        // Initialize WebDriver and navigate to URL
        // Task 1: Find and print total number of links
        // Task 2: Find and print total number of images
        // Task 3: Iterate and print each link's text
        // Task 4: Click on a product link using Link Text
        // Task 5: Verify page title and print verification result
        // Close the browser
    }
}

Hints:

  • Use driver.navigate().back() to return to the homepage after verifying page navigation.
  • Utilize driver.getTitle() to retrieve the current page title for verification.
  • Handle exceptions gracefully to ensure the script doesn’t terminate unexpectedly.

Next Steps

Congratulations on mastering the basics of locators and understanding the differences between findElement and findElements! In our upcoming sessions, we’ll advance to more complex locators and delve deeper into Actions you can perform on web elements.

Upcoming Topics:

  • CSS Selectors and XPath:
    • Crafting advanced selectors for dynamic and complex elements.
    • Best practices for writing maintainable XPath and CSS expressions.
  • Interacting with Web Elements:
    • Clicking buttons, entering text, selecting from dropdowns.
    • Handling checkboxes, radio buttons, and file uploads.
  • Advanced Validation Techniques:
    • Verifying element states and attributes.
    • Asserting page content and element properties.
  • Test Frameworks Integration:
    • Introducing TestNG for structured test management.
    • Generating comprehensive test reports.
  • Automation Best Practices:
    • Implementing the Page Object Model (POM) for scalable frameworks.
    • Utilizing design patterns to enhance code maintainability.

Stay tuned and continue practicing your locator strategies to build a strong foundation for your automation skills!

Conclusion

Effectively locating web elements is pivotal to successful web automation. By understanding and applying the various locator strategies—ranging from basic attributes like ID and Name to more customized approaches like XPath and CSS Selectors—you equip yourself to handle a wide array of scenarios in real-world applications. Coupled with the ability to perform actions on these elements, you can create comprehensive and reliable automation scripts that enhance testing efficiency and accuracy.

Keep experimenting with different locators, explore their strengths and limitations, and integrate best practices into your automation workflow. Happy automating!