Unit 3: Selenium Locators
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 uniqueid.By.name("username"): Matches thenameattribute.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 foundWebElementto 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 theidis 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
NoSuchElementExceptionif the element has not loaded, lies inside an iframe, or belongs to another window.
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.
findElement(By locator):- Returns one
WebElement, specifically the first matching element in DOM order. - Throws
NoSuchElementExceptionwhen no element matches.
- Returns one
findElements(By locator):- Returns
List<WebElement>. - Returns an empty list when no elements match; it does not throw
NoSuchElementException.
- Returns
- Scoped search:
form.findElement(By.name("password"))searches only inside theformelement. - 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.
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(), andgetAttribute("value")verify visibility, availability, and entered data. - Keyboard input:
sendKeys(Keys.ENTER)sends a named keyboard key. - Synchronization:
WebDriverWaitshould wait for visibility before typing into asynchronously rendered controls.
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:
ElementClickInterceptedExceptionindicates that an overlay, animation, or another element receives the click. - Accessibility anchor: A meaningful
altvalue may be useful, but it must be unique enough for reliable selection.
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.
- Checkbox:
- Use
isSelected()before clicking when the required final state is known. - Multiple checkboxes may remain selected simultaneously.
- Use
- Radio button:
- Locate the required option by
value,id, or associated label. - Selecting one radio button normally deselects another with the same
name.
- Locate the required option by
- 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.
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, notSelect.
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.
- Exact matching:
By.linkText("Account Settings")requires the complete visible text. - 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;
findElementchooses 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.
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, anddragAndDropmodel pointer behavior. - Keyboard operations:
keyDown,sendKeys, andkeyUpsupport modifier combinations such asCtrl+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
keyUpto avoid affecting later steps.
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/inputstarts 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 matchinactive; token-aware class matching is safer. - Axes:
following-sibling,preceding-sibling,parent, andancestorexpress relationships.
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.
- JavaScript alert:
- Use
driver.switchTo().alert()to obtain anAlert. - Call
accept()for OK,dismiss()for Cancel,getText()for its message, orsendKeys()for a prompt.
- Use
- Popup window or tab:
- Save the parent handle with
getWindowHandle(). - Read all handles with
getWindowHandles()and switch usingswitchTo().window(handle).
- Save the parent handle with
- 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
AlertAPI.
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, andgetAttribute("href")extracts resolved URLs. - Filtering: Skip null, empty, fragment-only,
javascript:,mailto:, andtel:destinations. - HTTP validation: Send an HTTP request and inspect the status code; responses in the
400–599range indicate client or server failure. - Redirect handling: Status codes
300–399are not automatically broken, but the final redirected destination should be checked. - Request method:
HEADreduces transferred content, although some servers reject it and requireGET. - Operational caution: Deduplicate URLs, use connection timeouts, respect authentication, and avoid aggressive request rates.
- Scope limitation: A successful
200response proves reachability, not that the destination contains correct content.
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.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →