Unit 3: Selenium Locators - Subjective Questions
CSE377 — Web Automation Testing • Practice Questions with Detailed Answers
20 questions
Define locators in Selenium WebDriver. Explain why locators are important in automated web testing and describe the commonly used locator strategies.
Locators are mechanisms used by Selenium WebDriver to identify and access HTML elements on a web page. They enable WebDriver to perform actions such as clicking, entering text, selecting options, and reading content.
Importance of locators:
- They establish a connection between the automation script and a web element.
- They allow Selenium to interact with dynamic web pages.
- Reliable locators improve test stability and maintainability.
- They help identify specific elements when many similar elements exist.
Common locator strategies:
idnameclassNametagNamelinkTextpartialLinkTextcssSelectorxpath
The best locator is generally unique, stable, readable, and independent of frequently changing page attributes.
Explain the difference between findElement() and findElements() in Selenium WebDriver with suitable examples.
findElement() and findElements() are used to locate web elements, but they differ in their return values and behavior.
findElement():
- Returns the first matching
WebElement. - Throws
NoSuchElementExceptionif no matching element is found. - Is suitable when one specific element is expected.
Example:
java
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
findElements():
- Returns a list of all matching elements.
- Returns an empty list when no matching elements are found.
- Is useful for handling multiple elements such as rows, links, or checkboxes.
Example:
java
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println(links.size());
The choice depends on whether the test requires one element or a collection of elements.
Describe the Selenium WebElement interface and explain the commonly used methods for interacting with form elements.
A WebElement represents an HTML element identified by Selenium WebDriver. It provides methods for inspecting the element and performing user-like actions.
Common methods:
click()selects buttons, links, checkboxes, and radio buttons.sendKeys()enters text into input fields.clear()removes existing text from an input field.getText()retrieves visible text.getAttribute()retrieves an HTML attribute value.isDisplayed()checks whether the element is visible.isEnabled()checks whether the element can be used.isSelected()checks the state of checkboxes and radio buttons.
Example:
java
WebElement email = driver.findElement(By.name("email"));
email.clear();
email.sendKeys("user@example.com");
WebElement submit = driver.findElement(By.id("submit"));
if (submit.isDisplayed() && submit.isEnabled()) {
submit.click();
}
These methods allow a test to interact with forms and verify element states.
Explain how to automate a form in Selenium WebDriver. Include the steps for locating fields, entering data, selecting controls, and submitting the form.
Automating a form involves identifying each control and performing actions in the same sequence as a user.
Typical procedure:
- Open the required page using
driver.get(). - Locate text fields using a suitable locator.
- Remove existing values with
clear()when necessary. - Enter data using
sendKeys(). - Select checkboxes or radio buttons using
click(). - Select a drop-down value using the
Selectclass. - Click the submit button.
- Verify the resulting page or message.
Example:
java
WebElement name = driver.findElement(By.id("name"));
name.sendKeys("Alex");
WebElement terms = driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
terms.click();
}
Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");
driver.findElement(By.id("submit")).click();
Validation should confirm that the form was submitted successfully and that error messages appear for invalid input.
Explain how to click an image in Selenium WebDriver. What conditions must be satisfied for the click operation to work reliably?
An image can be clicked when it is itself an interactive element or when it is placed inside a clickable link or button.
Procedure:
- Inspect the page and identify the image or its parent link.
- Choose a stable locator such as
id,cssSelector, orxpath. - Locate the element as a
WebElement. - Verify that it is visible and enabled.
- Use
click()or anActionsoperation.
Example:
java
WebElement image = driver.findElement(By.cssSelector("img[alt='Product']"));
if (image.isDisplayed() && image.isEnabled()) {
image.click();
}
If the image is nested inside an anchor element, clicking the anchor is often more reliable:
java
driver.findElement(By.cssSelector("a.product-link img")).click();
The element must be present in the DOM, visible, enabled, and unobstructed. Explicit waits may be required when the image is loaded dynamically.
Describe the method for selecting and validating checkboxes in Selenium WebDriver. How can a test avoid accidentally unchecking an already selected checkbox?
Checkboxes are generally selected or deselected by using the click() method. Their current state can be checked with isSelected().
Example:
java
WebElement newsletter = driver.findElement(By.id("newsletter"));
if (!newsletter.isSelected()) {
newsletter.click();
}
Important points:
- Use
isSelected()before clicking when the desired state is selected. - Do not click blindly because clicking an already selected checkbox will usually deselect it.
- Verify the final state after the action.
- Check
isDisplayed()andisEnabled()before interaction when the page contains dynamic controls.
For deselection:
java
if (newsletter.isSelected()) {
newsletter.click();
}
This approach makes the operation idempotent: running it repeatedly produces the same desired state.
Explain how radio buttons are handled in Selenium WebDriver. Compare radio buttons with checkboxes in terms of behavior and automation.
Radio buttons represent mutually exclusive choices within the same group. A user can normally select only one radio button from a group sharing the same name attribute.
Example:
java
WebElement male = driver.findElement(By.id("male"));
if (!male.isSelected() && male.isEnabled()) {
male.click();
}
Radio buttons:
- Usually permit only one selection in a group.
- Use
isSelected()to verify the selected option. - Selecting one option generally deselects another option in the same group.
Checkboxes:
- Usually allow multiple independent selections.
- Can be selected or deselected individually.
- Require state checks when a specific state is needed.
A robust test locates the required control, checks visibility and enabled status, clicks it only when necessary, and verifies the final selected state.
Explain how to select a value from a standard HTML drop-down using Selenium WebDriver's Select class. Describe its main selection methods.
The Selenium Select class is used with a standard HTML <select> element. First, the drop-down must be located and passed to the Select constructor.
Example:
java
WebElement countryElement = driver.findElement(By.id("country"));
Select country = new Select(countryElement);
country.selectByVisibleText("India");
Main selection methods:
selectByVisibleText(String text)selects the option displayed to the user.selectByValue(String value)selects an option using its HTMLvalueattribute.selectByIndex(int index)selects an option using its zero-based position.
Useful inspection methods:
getOptions()returns all options.getFirstSelectedOption()returns the selected option.isMultiple()checks whether multiple selections are allowed.
The Select class does not apply to custom drop-downs built with ordinary div or li elements. Such controls must be automated by locating and clicking their individual elements.
Compare locating elements by link text and partial link text in Selenium WebDriver. State their advantages, limitations, and appropriate use cases.
Link text locators identify anchor elements using the visible text of the link.
Exact link text:
java
driver.findElement(By.linkText("Contact Us")).click();
This requires the visible text to match exactly, including spaces and capitalization where applicable.
Partial link text:
java
driver.findElement(By.partialLinkText("Contact")).click();
This matches an anchor whose visible text contains the supplied substring.
Comparison:
linkTextis more precise and reduces accidental matches.partialLinkTextis useful when link text contains dynamic content or is lengthy.- Exact link text can fail when wording changes slightly.
- Partial matching can select the wrong link when several links contain the same text.
- Both strategies apply to links and are less suitable for non-anchor elements.
A unique CSS selector or XPath may be preferable when link text is duplicated or unstable.
Explain the purpose of the Selenium Actions class. Describe how it can be used for mouse and keyboard interactions with examples.
The Selenium Actions class supports complex user interactions that may not be handled adequately by a simple click() call.
Common operations:
- Mouse hover using
moveToElement(). - Right-click using
contextClick(). - Double-click using
doubleClick(). - Drag and drop using
dragAndDrop(). - Keyboard input using
keyDown(),keyUp(), andsendKeys().
Example:
java
WebElement menu = driver.findElement(By.id("menu"));
Actions actions = new Actions(driver);
actions.moveToElement(menu).perform();
Drag-and-drop example:
java
WebElement source = driver.findElement(By.id("source"));
WebElement target = driver.findElement(By.id("target"));
actions.dragAndDrop(source, target).perform();
perform() executes the built interaction. The class is useful for menus, sliders, hover effects, keyboard shortcuts, and coordinate-independent mouse actions.
Explain XPath in Selenium WebDriver. Distinguish between absolute XPath and relative XPath, and describe functions that make XPath useful for dynamic elements.
XPath is a query language used to navigate the HTML or XML structure of a document and locate elements.
Absolute XPath:
- Starts from the root of the document.
- Example:
/html/body/div/form/input - Is highly dependent on the complete page hierarchy.
- Is fragile when the page structure changes.
Relative XPath:
- Starts from a selected point using
//. - Example:
//input[@name='username'] - Is shorter, more readable, and generally more maintainable.
Useful XPath features:
- Attribute matching:
//input[@id='email'] - Text matching:
//button[text()='Login'] - Partial attribute matching:
//input[contains(@id,'user')] - Prefix matching:
//div[starts-with(@class,'panel')] - Multiple conditions:
//input[@type='text' and @name='email'] - Parent or sibling navigation using axes such as
parent,ancestor, andfollowing-sibling
XPath should be made as specific as necessary without depending on unstable indexes or excessive hierarchy.
Develop a reliable strategy for creating XPath expressions for dynamic web elements. Include examples using contains(), starts-with(), text matching, and multiple attributes.
Dynamic elements often have attributes whose values change between executions. A reliable XPath strategy focuses on stable attributes and relationships.
Recommended approach:
- Prefer unique and stable attributes such as
id,name, ordata-testid. - Use
contains()when only part of an attribute remains constant. - Use
starts-with()when an attribute has a stable prefix. - Combine multiple attributes to improve uniqueness.
- Use normalized text when spacing may vary.
- Avoid absolute paths and unnecessary numeric indexes.
Examples:
java
By userField = By.xpath("//input[contains(@id,'user')]");
By saveButton = By.xpath("//button[starts-with(@class,'save-')]");
By loginButton = By.xpath("//button[normalize-space()='Login']");
By emailField = By.xpath("//input[@type='email' and @name='email']");
The expression should be tested against the live DOM and should identify exactly the intended element. A locator that survives expected layout and content changes is preferable to one that merely works for the current page.
Explain how alerts are handled in Selenium WebDriver. Describe the operations required for simple alerts, confirmation alerts, and prompt alerts.
JavaScript alerts are handled using the Alert interface. WebDriver must switch from the web page context to the alert context before interacting with it.
Example:
java
Alert alert = driver.switchTo().alert();
String message = alert.getText();
alert.accept();
Types of alerts:
- Simple alert: Displays information and provides an OK button. Use
accept(). - Confirmation alert: Provides OK and Cancel options. Use
accept()to confirm ordismiss()to cancel. - Prompt alert: Accepts user input. Use
sendKeys()before accepting.
Prompt example:
java
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("Approved");
prompt.accept();
Useful methods include getText(), accept(), dismiss(), and sendKeys(). If an alert may not appear immediately, an explicit wait for alert presence should be used.
Explain how to handle popup windows or multiple browser windows in Selenium WebDriver. Describe the use of window handles.
Selenium identifies browser windows and tabs using unique window handles. A test can store the original handle, obtain all handles, switch to the required handle, perform actions, and return to the original window.
Example:
java
String parent = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
break;
}
}
System.out.println(driver.getTitle());
driver.close();
driver.switchTo().window(parent);
Important practices:
- Use
getWindowHandle()for the current window. - Use
getWindowHandles()for all open windows or tabs. - Switch before locating elements in another window.
- Use
close()for the current window andquit()for the entire browser session. - Wait for the new window when it opens asynchronously.
Window handles are different from JavaScript alerts and should not be handled with switchTo().alert().
Differentiate between a JavaScript alert, a browser window popup, and an HTML modal popup in Selenium WebDriver. Explain how each is handled.
These popup types require different handling techniques.
JavaScript alert:
- Is managed by the browser alert interface.
- Does not belong to the normal HTML DOM.
- Handled with
driver.switchTo().alert()followed byaccept(),dismiss(), orsendKeys().
Browser window or tab popup:
- Has its own window handle.
- Handled with
getWindowHandle(),getWindowHandles(), andswitchTo().window(handle).
HTML modal popup:
- Is an ordinary DOM element, often created using
div,section, or a framework component. - Handled by locating its elements with normal locators such as CSS selectors or XPath.
Example for an HTML modal:
java
driver.findElement(By.cssSelector(".modal .close")).click();
Correct classification is essential. Using alert APIs for an HTML modal or window handles for a JavaScript alert will cause failures.
Describe the process of finding broken links using Selenium WebDriver. Explain how HTTP response codes are used to identify broken links.
A broken link points to a resource that cannot be successfully retrieved. Selenium can collect links from a page, while an HTTP client checks the response status of each URL.
Process:
- Locate all anchor elements using
findElements(By.tagName("a")). - Read each link's
hrefattribute. - Skip null, empty, JavaScript, mailto, and fragment-only links when appropriate.
- Send an HTTP request to each valid URL.
- Read the response status code.
- Classify the link based on the response.
Typical interpretation:
2xx: successful response.3xx: redirection, usually not broken but may require policy checks.4xx: client-side error, such as not found or forbidden.5xx: server-side error.
Example outline:
java
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String href = link.getAttribute("href");
// Validate the URL and inspect its HTTP response status.
}
The test should report the URL, status code, and classification for every failed request.
Write and explain a Selenium WebDriver approach for validating all links on a page, including handling null URLs, redirects, exceptions, and resource cleanup.
A robust broken-link test must handle invalid attributes and network failures without stopping after the first problem.
Recommended approach:
- Collect all anchor elements.
- Read and trim the
hrefattribute. - Ignore null, blank, and unsupported schemes.
- Create an HTTP request with a reasonable timeout.
- Inspect the response code.
- Treat configured
4xxand5xxresponses as failures. - Catch connection and timeout exceptions.
- Close the HTTP response and client resources.
Example structure:
java
for (WebElement element : driver.findElements(By.cssSelector("a[href]"))) {
String href = element.getAttribute("href");
if (href == null || href.isBlank() || href.startsWith("javascript:")) {
continue;
}
try {
// Send an HTTP request, inspect the status code, and record the result.
} catch (Exception exception) {
// Record the URL as unreachable with the exception details.
}
}
The report should distinguish broken links from links skipped by policy, redirects, and links that could not be tested because of network errors.
Explain how explicit waits improve the reliability of Selenium locator operations. Discuss why an element may be located successfully but still fail during interaction.
Finding an element in the DOM does not guarantee that it is ready for interaction. The element may be hidden, disabled, covered by another element, or still changing because of asynchronous page activity.
Explicit waits pause execution until a specified condition is satisfied.
Example:
java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement login = wait.until(
ExpectedConditions.elementToBeClickable(By.id("login"))
);
login.click();
Useful conditions include:
presenceOfElementLocated()for DOM presence.visibilityOfElementLocated()for visibility.elementToBeClickable()for enabled and clickable controls.alertIsPresent()for JavaScript alerts.numberOfWindowsToBe()for popup windows.
Explicit waits reduce timing-related failures and are more targeted than fixed delays. Tests should avoid mixing implicit and explicit waits unnecessarily because the combined timing can become difficult to predict.
Compare different Selenium locator strategies in terms of speed, stability, readability, and maintainability. Recommend a locator priority order for a test project.
Locator strategies differ in their stability and dependency on the page structure.
Comparison:
id: Usually fast, readable, and stable when uniquely assigned.name: Useful when the value is stable and unique.className: Convenient but risky when classes are generated or shared.tagName: Rarely unique and generally used to collect groups of elements.linkText: Readable but dependent on visible wording.partialLinkText: Flexible but may match unintended links.cssSelector: Powerful, concise, and often efficient.xpath: Supports complex relationships and text conditions but can become fragile when overly dependent on hierarchy.
A practical priority order is:
- Stable unique
idor test-specific attribute. - Stable
nameor accessible attribute. - CSS selector.
- Relative XPath.
- Link text or partial link text when the link wording is stable.
- Tag name for collections rather than individual controls.
The ideal choice is the locator that is unique, meaningful, and resistant to expected UI changes.
Explain the common exceptions related to Selenium locators and interactions. State the likely causes and suitable remedies for each exception.
Selenium exceptions often indicate that the page state or locator assumption does not match the test.
Common exceptions and remedies:
NoSuchElementException: The locator is incorrect or the element is not present. Recheck the locator and use an appropriate wait.StaleElementReferenceException: The DOM was refreshed or replaced. Locate the element again after the update.ElementNotInteractableException: The element is hidden or disabled. Wait for visibility or enablement and verify the correct control.ElementClickInterceptedException: Another element covers the target. Wait for overlays to disappear or interact with the correct visible element.TimeoutException: A required condition was not met. Check page behavior, timeout duration, and locator correctness.NoAlertPresentException: The script attempted to switch to an alert that was not open. Wait for the alert or verify that the action triggered it.NoSuchWindowException: The selected window was closed or its handle is invalid. Recheck window switching logic.
Good diagnostics include capturing the page state, locator, current URL, and relevant exception message.
Define locators in Selenium WebDriver. Explain why locators are important in automated web testing and describe the commonly used locator strategies.
Locators are mechanisms used by Selenium WebDriver to identify and access HTML elements on a web page. They enable WebDriver to perform actions such as clicking, entering text, selecting options, and reading content.
Importance of locators:
- They establish a connection between the automation script and a web element.
- They allow Selenium to interact with dynamic web pages.
- Reliable locators improve test stability and maintainability.
- They help identify specific elements when many similar elements exist.
Common locator strategies:
idnameclassNametagNamelinkTextpartialLinkTextcssSelectorxpath
The best locator is generally unique, stable, readable, and independent of frequently changing page attributes.
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 →