Unit 3: Selenium Locators

CSE377 — Web Automation Testing 9 min read

I. Orientation — Identifying and Interacting with Web Elements

Selenium WebDriver is a browser-automation API used to locate HTML elements, inspect their state, and perform user-like operations. A locator defines how WebDriver searches the Document Object Model (DOM) for an element such as an input, link, image, button, or list.

  • Governing principle: WebDriver first establishes a browsing context, then finds an element within the current DOM and performs an operation on the returned WebElement.
  • Main locator strategies:
    • By.id("email"): Matches an element's unique id.
    • By.name("username"): Matches the name attribute.
    • By.className("submit-button"): Matches one CSS class.
    • By.tagName("input"): Matches an HTML tag.
    • By.cssSelector("#login input"): Uses a CSS selector.
    • By.xpath("//button[@type='submit']"): Uses an XPath expression.
    • By.linkText("Home"): Matches complete visible link text.
    • By.partialLinkText("Hom"): Matches part of visible link text.
  • Preferred locator qualities: A good locator is unique, stable, readable, and independent of changing layout or generated attribute values.
  • Element context: Searches normally begin from driver, but they may begin from a previously found WebElement to limit the search to one DOM subtree.
  • Synchronization requirement: Dynamic elements may require explicit waits because presence, visibility, and clickability are different conditions.

II. Locator Fundamentals — Search Strategies and Reliability

A. Introduction to Locators in Selenium WebDriver

A Selenium locator is a query that identifies one or more DOM nodes so WebDriver can interact with them.

  • ID locator: By.id("loginButton") is usually concise and dependable when the id is unique and stable.
  • CSS locator: By.cssSelector("form#login input[name='email']") combines tags, attributes, IDs, and hierarchy efficiently.
  • XPath locator: By.xpath("//form[@id='login']//input[@name='email']") supports relationships, text matching, and complex DOM navigation.
  • Stability rule: Prefer dedicated attributes such as data-testid="checkout" over positional expressions such as (//button)[3].
  • Uniqueness check: Browser developer tools can verify that a selector matches exactly one intended node.
  • Common failure: A valid locator may still raise NoSuchElementException if the element has not loaded, lies inside an iframe, or belongs to another window.
JAVA
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("learner@example.com");

Here, driver is the WebDriver session and email is the located WebElement.

III. Element Retrieval — Singular and Collection Searches

A. FindElement and FindElements in Selenium WebDriver

findElement returns the first match, whereas findElements returns every match as a list.

  1. findElement(By locator):
    • Returns one WebElement, specifically the first matching element in DOM order.
    • Throws NoSuchElementException when no element matches.
  2. findElements(By locator):
    • Returns List<WebElement>.
    • Returns an empty list when no elements match; it does not throw NoSuchElementException.
  • Scoped search: form.findElement(By.name("password")) searches only inside the form element.
  • Presence limitation: Retrieval does not guarantee that an element is visible, enabled, or clickable.
  • Collection use: Lists are suitable for tables, menus, search results, and repeated product elements.
JAVA
List<WebElement> rows = driver.findElements(By.cssSelector("table tbody tr"));
System.out.println(rows.size());

IV. Form Interaction — Entering and Submitting Data

A. Selenium Form WebElement

A form WebElement exposes fields and controls through methods that simulate browser interactions.

  • Text entry: sendKeys("Alice") enters text into an <input> or <textarea>.
  • Replacement: clear() removes existing editable content before new input is sent.
  • Submission: submit() submits the containing form, although clicking its explicit submit button more closely represents normal user behavior.
  • State inspection: isDisplayed(), isEnabled(), and getAttribute("value") verify visibility, availability, and entered data.
  • Keyboard input: sendKeys(Keys.ENTER) sends a named keyboard key.
  • Synchronization: WebDriverWait should wait for visibility before typing into asynchronously rendered controls.
JAVA
WebElement username = driver.findElement(By.name("username"));
username.clear();
username.sendKeys("alice");
driver.findElement(By.cssSelector("button[type='submit']")).click();

V. Image Interaction — Clickable Visual Elements

A. Clicking on Image in Selenium WebDriver

An image can be clicked when the <img> itself or its enclosing element has an associated action.

  • Direct image: Locate an image by stable attributes, for example By.cssSelector("img[alt='Company home']").
  • Linked image: If markup is <a href="/"><img alt="Home"></a>, locating the <a> often expresses the clickable target more accurately.
  • Readiness check: Wait for elementToBeClickable, which requires visibility and enabled state.
  • Obstruction risk: ElementClickInterceptedException indicates that an overlay, animation, or another element receives the click.
  • Accessibility anchor: A meaningful alt value may be useful, but it must be unique enough for reliable selection.
JAVA
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement logo = wait.until(ExpectedConditions.elementToBeClickable(
    By.cssSelector("a.home-link img[alt='Home']")));
logo.click();

VI. Choice Controls — Binary and Exclusive Selection

A. Selecting CheckBox and Radio Button in Selenium WebDriver

Checkboxes permit independent selections, while radio buttons normally permit one selection within a named group.

  1. Checkbox:
    • Use isSelected() before clicking when the required final state is known.
    • Multiple checkboxes may remain selected simultaneously.
  2. Radio button:
    • Locate the required option by value, id, or associated label.
    • Selecting one radio button normally deselects another with the same name.
  • Idempotent selection: Conditional clicking prevents a checked checkbox from being accidentally cleared.
  • Label interaction: Clicking <label for="standard"> can be more representative when the input is visually hidden.
  • Verification: Assert isSelected() after the operation.
JAVA
WebElement terms = driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
    terms.click();
}
driver.findElement(By.cssSelector("input[name='plan'][value='standard']")).click();

VII. Dropdown Controls — Selecting Native Options

A. Select Value from DropDown using Selenium WebDriver

Selenium's Select class operates on native HTML <select> elements and exposes their <option> choices.

  • Visible text: selectByVisibleText("India") matches displayed option text.
  • Attribute value: selectByValue("IN") matches <option value="IN">.
  • Position: selectByIndex(2) uses zero-based option order and is more fragile when options change.
  • Inspection: getFirstSelectedOption() returns the current choice.
  • Multiple selection: isMultiple() identifies a multi-select; deselectAll() clears its selections.
  • Limitation: Custom JavaScript dropdowns built from <div> and <li> elements require ordinary clicks, not Select.
JAVA
Select country = new Select(driver.findElement(By.id("country")));
country.selectByValue("IN");
String chosen = country.getFirstSelectedOption().getText();

VIII. Hyperlink Location — Matching Visible Anchor Text

A. Locate Elements by Link Text and Partial Link Text in Selenium WebDriver

Link-text locators identify anchor elements through the visible text rendered for users.

  1. Exact matching: By.linkText("Account Settings") requires the complete visible text.
  2. Partial matching: By.partialLinkText("Account") accepts a substring and may match several links.
  • Applicable element: These strategies are intended for <a> elements, not arbitrary buttons or paragraphs.
  • Ambiguity: Partial text is less precise; findElement chooses the first matching anchor in DOM order.
  • Whitespace and rendering: Nested spans and normalized visible text can affect matching, so CSS selectors may be more stable.
  • Internationalization: Text-based locators can fail when the interface language changes.
  • Collection search: findElements(By.partialLinkText("Learn")) can retrieve all matching links.
JAVA
driver.findElement(By.linkText("Contact Us")).click();

IX. Advanced User Input — Composite Gestures

A. Action Class in Selenium WebDriver

The Actions class builds complex mouse and keyboard interactions and executes them as a sequence.

  • Mouse operations: moveToElement, click, doubleClick, contextClick, and dragAndDrop model pointer behavior.
  • Keyboard operations: keyDown, sendKeys, and keyUp support modifier combinations such as Ctrl+A.
  • Execution rule: Chained actions do nothing until perform() is called; build().perform() explicitly builds and executes the sequence.
  • Hover menus: moveToElement(menu).perform() can reveal controls activated by CSS hover behavior.
  • Drag limitations: Applications using custom pointer-event libraries may require offset-based movements.
  • State discipline: Every pressed modifier should be released with keyUp to avoid affecting later steps.
JAVA
Actions actions = new Actions(driver);
actions.moveToElement(menu)
       .click(submenu)
       .perform();

X. XPath Expressions — Structural DOM Queries

A. XPath in Selenium WebDriver

XPath locates nodes through attributes, text, hierarchy, predicates, and relationships within the DOM.

  • Absolute XPath: /html/body/div/form/input starts at the document root and breaks easily when layout changes.
  • Relative XPath: //input[@name='email'] searches from the current context and is generally more maintainable.
  • Predicates: //button[@type='submit' and @name='save'] filters by multiple conditions.
  • Text functions: //button[normalize-space()='Save'] matches normalized visible text.
  • Partial matching: contains(@class,'active') is useful but can accidentally match inactive; token-aware class matching is safer.
  • Axes: following-sibling, preceding-sibling, parent, and ancestor express relationships.
JAVA
WebElement price = driver.findElement(
    By.xpath("//tr[td[normalize-space()='Keyboard']]/td[@class='price']")
);

This expression finds the price cell in the row whose data cell contains Keyboard.

XI. Browser Interruptions — Alerts and Secondary Contexts

A. Alert and Popup Window Handling in Selenium WebDriver

Alerts require switching to an alert context, while popup windows require switching to another window handle.

  1. JavaScript alert:
    • Use driver.switchTo().alert() to obtain an Alert.
    • Call accept() for OK, dismiss() for Cancel, getText() for its message, or sendKeys() for a prompt.
  2. Popup window or tab:
    • Save the parent handle with getWindowHandle().
    • Read all handles with getWindowHandles() and switch using switchTo().window(handle).
  • Explicit wait: ExpectedConditions.alertIsPresent() prevents premature switching.
  • Context restoration: After closing a child window, switch back to the saved parent handle.
  • Distinction: HTML modal dialogs are DOM elements and must be handled with locators, not the Alert API.
JAVA
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(10))
    .until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
alert.accept();

XII. Link Validation — Detecting Unreachable Resources

A. Finding Broken Links using Selenium WebDriver

Broken-link checking combines Selenium link discovery with HTTP requests that validate each destination.

  • Discovery: findElements(By.tagName("a")) collects anchors, and getAttribute("href") extracts resolved URLs.
  • Filtering: Skip null, empty, fragment-only, javascript:, mailto:, and tel: destinations.
  • HTTP validation: Send an HTTP request and inspect the status code; responses in the 400–599 range indicate client or server failure.
  • Redirect handling: Status codes 300–399 are not automatically broken, but the final redirected destination should be checked.
  • Request method: HEAD reduces transferred content, although some servers reject it and require GET.
  • Operational caution: Deduplicate URLs, use connection timeouts, respect authentication, and avoid aggressive request rates.
  • Scope limitation: A successful 200 response proves reachability, not that the destination contains correct content.
JAVA
HttpURLConnection connection =
    (HttpURLConnection) new URL(href).openConnection();
connection.setRequestMethod("HEAD");
connection.setConnectTimeout(5000);
connection.connect();

int status = connection.getResponseCode();
boolean broken = status >= 400;
connection.disconnect();

Here, href is the destination URL, status is the HTTP response code, and broken records whether the response indicates failure.