0
0
Selenium Javatesting~15 mins

findElement by ID in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify login button is clickable using findElement by ID
Preconditions (1)
Step 1: Locate the login button using its ID 'loginBtn'
Step 2: Click the login button
✅ Expected Result: The login button is found by ID and clicked successfully without errors
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the login button is displayed before clicking
Verify the login button is enabled before clicking
Best Practices:
Use By.id locator for finding the element
Use explicit waits to wait for the element to be clickable
Use try-catch to handle NoSuchElementException
Close the browser after test execution
Automated Solution
Selenium Java
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.

Common Mistakes - 3 Pitfalls
Using driver.findElement without waiting for the element to be present or clickable
Using incorrect locator type or wrong ID value
Not closing the browser after test execution
Bonus Challenge

Now add data-driven testing with 3 different button IDs to verify each button is clickable

Show Hint