Good selectors help your tests find the right parts of a webpage every time. This stops tests from breaking when small page changes happen.
When writing tests that click buttons or fill forms on a webpage
When checking if a webpage shows the correct information
When automating repetitive tasks on websites
When maintaining tests that run often and must be reliable
Syntax
Selenium Java
By locator = By.method("value");
By is a Selenium class to find elements.
Common methods: id, name, cssSelector, xpath.
Examples
Finds element with id 'submit-button'. This is fast and reliable if id is unique.
Selenium Java
By idLocator = By.id("submit-button");
Finds a button with class 'primary'. Useful when id is missing.
Selenium Java
By cssLocator = By.cssSelector("button.primary");
Finds a link with text 'Home' inside a div with class 'menu'. XPath is flexible but can be fragile if page structure changes.
Selenium Java
By xpathLocator = By.xpath("//div[@class='menu']//a[text()='Home']");
Sample Program
This test opens a login page, fills username and password using strong selectors, clicks login, and checks if login succeeded by looking for a logout button.
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SelectorMasteryTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com/login");
// Use strong selector by id
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("testuser");
// Use strong selector by css class
WebElement password = driver.findElement(By.cssSelector("input.password-field"));
password.sendKeys("password123");
// Use strong selector by xpath
WebElement loginButton = driver.findElement(By.xpath("//button[@type='submit']"));
loginButton.click();
// Check if login was successful by presence of logout button
boolean loggedIn = driver.findElements(By.id("logout")).size() > 0;
System.out.println("Login success: " + loggedIn);
} finally {
driver.quit();
}
}
}
OutputSuccess
Important Notes
Always prefer unique and stable attributes like id or name for selectors.
Avoid using selectors that depend on page layout or text that might change often.
Test selectors regularly to catch changes early and keep tests reliable.
Summary
Good selectors make tests stable and less likely to break.
Use unique attributes like id or name whenever possible.
Test and update selectors as the webpage changes.
Practice
(1/5)
1. Why is it important to use unique attributes like id or name in Selenium selectors?
easy
A. They are harder to write and maintain.
B. They slow down the test execution significantly.
C. They always cause tests to fail.
D. They make tests more stable and less likely to break when the page changes.
Solution
Step 1: Understand selector uniqueness
Unique attributes like id or name identify elements clearly without confusion.
Step 2: Impact on test stability
Using unique selectors reduces the chance tests break when page layout or styles change.
Final Answer:
They make tests more stable and less likely to break when the page changes. -> Option D
Quick Check:
Unique selectors = stable tests [OK]
Hint: Pick selectors with unique attributes for stable tests [OK]
Common Mistakes:
Choosing selectors based on visible text only
Using generic tags like div without attributes
Ignoring the importance of uniqueness
2. Which of the following is the correct syntax to locate an element by its id in Selenium Java?
easy
A. driver.findElement(By.id("submitBtn"));
B. driver.findElement(By.name="submitBtn");
C. driver.findElement(By.className("submitBtn"));
D. driver.findElement(By.tag("submitBtn"));
Solution
Step 1: Recall Selenium locator syntax
The correct method to find by id is By.id("value").
Step 2: Check each option
driver.findElement(By.id("submitBtn")); uses By.id("submitBtn"), which is correct syntax. Others use incorrect methods or syntax.
Final Answer:
driver.findElement(By.id("submitBtn")); -> Option A
Quick Check:
Use By.id("...") for id selectors [OK]
Hint: Use By.id("...") to select by id attribute [OK]
Common Mistakes:
Using assignment (=) instead of method parameter syntax
Confusing By.name and By.id
Using non-existent locator methods like By.tag
3. Given the following code snippet, what will be the output if the element with id loginBtn is not present on the page?
If the element is missing, findElement throws NoSuchElementException.
Step 2: Analyze try-catch block
The exception is caught, so the catch block prints "Button not found".
Final Answer:
Button not found -> Option B
Quick Check:
Missing element triggers catch block [OK]
Hint: Missing element triggers NoSuchElementException catch [OK]
Common Mistakes:
Assuming findElement returns null if not found
Ignoring exception handling
Confusing findElement with findElements
4. You wrote this selector: driver.findElement(By.xpath("//div[@class='btn']")). Your test breaks when the page adds another div with class btn. How can you fix this fragile selector?
medium
A. Use Thread.sleep() before finding the element.
B. Change the selector to By.tagName("div") to select all divs.
C. Use a more specific attribute like an id or unique data-test attribute.
D. Remove the class condition and select by div only.
Solution
Step 1: Identify fragility cause
The selector matches multiple elements because class btn is not unique.
Step 2: Improve selector specificity
Using a unique attribute like id or data-test makes the selector stable and precise.
Final Answer:
Use a more specific attribute like an id or unique data-test attribute. -> Option C
Quick Check:
Specific unique attributes prevent fragile selectors [OK]
Hint: Pick unique attributes to avoid multiple matches [OK]
Common Mistakes:
Selecting all divs causes more fragility
Ignoring selector uniqueness
Using waits instead of fixing selectors
5. You have a test that uses this selector: driver.findElement(By.cssSelector("button.submit-btn")) After a page update, the class name changes to submit-button. What is the best way to prevent such fragile tests in the future?
hard
A. Ask developers to add a unique data-test attribute and use it in selectors.
B. Use XPath with contains() to match partial class names.
C. Use absolute XPath from the root element to the button.
D. Avoid using selectors and rely on screen coordinates.
Solution
Step 1: Understand fragility cause
Class names often change due to styling updates, breaking selectors based on them.
Step 2: Use stable attributes for selectors
Unique data-test attributes are designed for testing and rarely change, making tests stable.
Final Answer:
Ask developers to add a unique data-test attribute and use it in selectors. -> Option A
Quick Check:
Stable test attributes prevent fragile selectors [OK]
Hint: Use dedicated test attributes like data-test for stable selectors [OK]
Common Mistakes:
Using fragile class names in selectors
Using absolute XPath which breaks easily
Relying on screen coordinates which are unreliable
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.