findElement by ID in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class FindElementByIdTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("http://example.com/login"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn"))); if (loginButton.isDisplayed() && loginButton.isEnabled()) { loginButton.click(); System.out.println("Login button clicked successfully."); } else { System.out.println("Login button is not ready for clicking."); } } catch (Exception e) { System.out.println("Exception occurred: " + e.getMessage()); } finally { driver.quit(); } } }
This code uses Selenium WebDriver with Java to automate the manual test case.
First, it sets up the ChromeDriver and opens the login page URL.
It uses WebDriverWait with ExpectedConditions.elementToBeClickable to wait until the login button with ID loginBtn is clickable. This avoids timing issues.
Then it checks if the button is displayed and enabled before clicking it, ensuring the element is interactable.
If the button is ready, it clicks the button and prints a success message.
Any exceptions are caught and printed to help debug failures.
Finally, the browser is closed with driver.quit() to clean up resources.
Now add data-driven testing with 3 different button IDs to verify each button is clickable
Practice
findElement(By.id("submitBtn")) do?Solution
Step 1: Understand the method purpose
The methodfindElementlocates a single web element on the page.Step 2: Analyze the locator used
UsingBy.id("submitBtn")means it looks for an element with the exact ID "submitBtn".Final Answer:
Finds the first element on the page with the ID "submitBtn". -> Option BQuick Check:
findElement + By.id = single element by ID [OK]
- Confusing findElement with findElements (plural)
- Using class name or tag name instead of ID
- Assuming it returns multiple elements
Solution
Step 1: Recall correct method syntax
The methodBy.idis called with parentheses and a string argument, likeBy.id("username").Step 2: Check Java case sensitivity
Java is case-sensitive, soBy.idmust be lowercase 'id', and parentheses are required.Final Answer:
driver.findElement(By.id("username")); -> Option DQuick Check:
Correct method call syntax = driver.findElement(By.id("username")); [OK]
- Using assignment '=' instead of parentheses
- Wrong capitalization like By.ID or By.Id
- Missing parentheses around the ID string
WebElement button = driver.findElement(By.id("loginBtn"));
button.click();Solution
Step 1: Understand findElement behavior when element missing
If no element matches the ID,findElementthrowsNoSuchElementExceptionimmediately.Step 2: Analyze code flow
The exception occurs at thefindElementline, sobutton.click()is never reached.Final Answer:
Throws NoSuchElementException at findElement line. -> Option AQuick Check:
Missing element causes NoSuchElementException [OK]
- Assuming findElement returns null if element missing
- Expecting NullPointerException instead
- Thinking click() runs even if element not found
WebElement input = driver.findElement(By.id("email"));
input.sendKeys("test@example.com");
WebElement submit = driver.findElement(By.id("submit"));
submit.click();
Assuming the page has no element with ID "submit".Solution
Step 1: Check element existence for each findElement
The element with ID "email" exists, sosendKeysworks fine.Step 2: Analyze finding "submit" element
Since "submit" ID does not exist,findElement(By.id("submit"))throwsNoSuchElementException.Final Answer:
Throws NoSuchElementException at finding "submit" element. -> Option CQuick Check:
Missing ID causes NoSuchElementException [OK]
- Assuming sendKeys fails if element missing later
- Confusing exceptions thrown at different lines
- Expecting click() to throw error instead of findElement
Solution
Step 1: Understand the problem
The button with ID "submitBtn" might not exist, so clicking it directly may cause an exception.Step 2: Evaluate each option
driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); driver.findElement(By.id("submitBtn")).click(); clicks without checking, risking failure. driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); WebElement btn = driver.findElement(By.id("submitBtn")); if(btn != null) { btn.click(); } attempts null check but throws NoSuchElementException at findElement since it never returns null. driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); try { driver.findElement(By.id("submitBtn")).click(); } catch (NoSuchElementException e) { System.out.println("Button not found, skipping click."); } uses try-catch to handle missing button gracefully. driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); WebElement btn = null; btn.click(); assigns null and calls click(), causing NullPointerException.Final Answer:
Use try-catch to handle missing element and avoid failure. -> Option AQuick Check:
Try-catch handles missing element safely [OK]
- Not handling missing elements causing test failure
- Calling click() on null element
- Assuming findElement returns null if element is missing
Ready to prove it?
Pass the test and this pattern moves unknown
