Open In App

Selenium WebDriver - WebElement Commands Using Java

Last Updated : 26 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

WebElement commands are methods used to interact with web elements like buttons, text fields, and links on a webpage. These commands allow automation scripts to perform actions like clicking, entering text, retrieving attributes, or verifying element states.

These WebElement commands make automation tasks easier by providing reliable and efficient ways to interact with web elements in Selenium WebDriver.

Syntax:

The click() method is used to perform a mouse click on a web element. Similarly, we can declare a different WebElement and use it in automation testing.

WebElement clickbtn = driver.findElement(By.id("submitButton"));
clickbtn.click();

WebElement Commands

These WebElement commands in Selenium WebDriver simplify automation testing by enabling reliable interactions with web elements.

1. sendKeys()

Use the sendKeys() method to send keyboard input to an element, like typing in a text field or pressing keys (e.g., Enter).

WebElement inputField = driver.findElement(By.id("username"));
inputField.sendKeys("testUser");

2. isDisplayed()

Use the isDisplayed() method to check if an element is visible on the page. It returns true if visible, otherwise throws a NoSuchElementException.

WebElement element = driver.findElement(By.id("image"));
boolean isVisible = element.isDisplayed();
System.out.println("Element is visible: " + isVisible);

3. isSelected()

Use the isSelected() method to check if an element like a checkbox or radio button is selected.

WebElement checkbox = driver.findElement(By.id("acceptTerms"));
boolean isSelected = checkbox.isSelected();
System.out.println("Checkbox is selected: " + isSelected);

4. submit()

Use the submit() method to submit a form. It works on <form> elements or inputs within forms.

WebElement submitButton = driver.findElement(By.id("loginForm"));
submitButton.submit();

5. isEnabled()

Use the isEnabled() method to check if an element is interactable (not disabled).

WebElement button = driver.findElement(By.id("submitButton"));
boolean isEnabled = button.isEnabled();
System.out.println("Button is enabled: " + isEnabled);

6. getLocation()

Use the getLocation() method to retrieve an element’s position on the page as x, y coordinates.

WebElement element = driver.findElement(By.id("image"));
Point location = element.getLocation();
System.out.println("Element location: x = " + location.getX() + ", y = " + location.getY());

7. clear()

Use the clear() method to clear the text in an input or textarea element.

WebElement inputField = driver.findElement(By.id("username"));
inputField.clear();

8. getText()

Use the getText() method to retrieve the visible text of an element or its inner text.

WebElement heading = driver.findElement(By.tagName("h1"));
String headingText = heading.getText();
System.out.println("Heading text: " + headingText);

9. getTagName()

Use the getTagName() method to retrieve the HTML tag name of the element.

WebElement button = driver.findElement(By.id("submitButton"));
String tagName = button.getTagName();
System.out.println("Tag name: " + tagName);

10. getCssValue()

Use the getCssValue() method to retrieve the value of a CSS property (e.g., color, padding).).

WebElement element = driver.findElement(By.id("image"));
String color = element.getCssValue("color");
System.out.println("Element color: " + color);

11. getAttribute()

Use the getAttribute() method to get the value of an HTML attribute (e.g., href, class, value).

WebElement link = driver.findElement(By.linkText("Click Here"));
String hrefValue = link.getAttribute("href");
System.out.println("Link href value: " + hrefValue);

12. getSize()

Use the getSize() method to get the dimensions (width and height) of an element as a Dimension object.

WebElement element = driver.findElement(By.id("image"));
Dimension size = element.getSize();
System.out.println("Element size: width = " + size.getWidth() + ", height = " + size.getHeight());

Example of WebElement Commands

Here’s a complete example which include various WebElement commands using Selenium WebDriver, interacting with the Saucedemo website, with proper setup and error handling.

Java
package Tests;

import java.time.Duration;
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.chrome.ChromeOptions;

public class WebElementCommandsTest {
    public static void main(String[] args) {
        // Manually set the path to chromedriver executable
        System.setProperty("webdriver.chrome.driver", "C:\\path of the Chromedriver\\chromedriver.exe");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver(options);

        try {
            // Navigate to Saucedemo
            driver.get("https://www.saucedemo.com/");
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

            // 1. sendKeys: Enter username and password
            WebElement username = driver.findElement(By.id("user-name"));
            username.sendKeys("standard_user");
            WebElement password = driver.findElement(By.id("password"));
            password.sendKeys("secret_sauce");
            System.out.println("Entered credentials.");

            // 2. isDisplayed: Check if login button is visible
            WebElement loginButton = driver.findElement(By.id("login-button"));
            System.out.println("Is login button displayed? " + loginButton.isDisplayed());

            // 3. isEnabled: Check if login button is enabled
            System.out.println("Is login button enabled? " + loginButton.isEnabled());

            // 4. getLocation: Get login button coordinates
            System.out.println("Login button location: " + loginButton.getLocation());

            // 5. getSize: Get login button size
            System.out.println("Login button size: " + loginButton.getSize());

            // 6. getCssValue: Get login button background color
            System.out.println("Login button background: " + loginButton.getCssValue("background-color"));

            // 7. getAttribute: Get login button value attribute
            System.out.println("Login button value: " + loginButton.getAttribute("value"));

            // 8. getTagName: Get login button tag
            System.out.println("Login button tag: " + loginButton.getTagName());

            // 9. click: Click login button
            loginButton.click();
            System.out.println("Clicked login button.");

            // 10. getText: Get page title after login
            WebElement title = driver.findElement(By.className("title"));
            System.out.println("Page title: " + title.getText());

            // 11. isSelected: Check if filter dropdown is selected
            WebElement filter = driver.findElement(By.className("product_sort_container"));
            System.out.println("Is filter selected? " + filter.isSelected());

            // 12. clear: Clear and re-enter username after failed login
            driver.get("https://www.saucedemo.com/"); // Reload page
            username = driver.findElement(By.id("user-name"));
            username.sendKeys("invalid_user");
            username.clear();
            username.sendKeys("standard_user");
            System.out.println("Cleared and re-entered username.");

            // 13. submit: Submit login form
            loginButton = driver.findElement(By.id("login-button"));
            loginButton.submit();
            System.out.println("Submitted login form.");

            // Pause to observe results
            Thread.sleep(5000);
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        } finally {
            // Close browser
            driver.quit();
        }
    }
}

Output:

WebElements-Commands-Output
WebElements Commands Output

Best Practices of WebElement Commands

Follow best practices for using WebElement commands in Selenium WebDriver for easier automation:

  1. Use Explicit Waits: Explicit waits help manage dynamic elements, ensuring that actions are performed only when the elements are ready (e.g., using WebDriverWait with elementToBeClickable() before clicking on a button). This avoids unnecessary delays and makes your tests more reliable.
  2. Validate Locators: Before using locators like By.id, By.name, or By.xpath, test them in the browser’s developer tools (F12) to confirm their accuracy. This helps avoid issues with incorrect locators that can break tests.
  3. Handle Exceptions: Wrap your WebElement commands in try-catch blocks to handle common exceptions like NoSuchElementException. This will allow your tests to fail gracefully and provide useful error messages for debugging.
  4. Prioritize Stable Attributes: Choose locators based on stable and unique attributes, such as id or name. XPath locators tend to be slower and more fragile, so use them sparingly.
  5. Log Results: Print out the results of commands (like getText() or getAttribute()) for debugging purposes. This provides insights into what is happening at each step, especially when testing with dynamic data.
  6. Test Real Scenarios: Use real-world testing scenarios, such as those found on platforms like Saucedemo, to simulate actions like form submissions, logins, and e-commerce navigation. This ensures that your tests mimic user behavior accurately.
  7. Keep Tests Modular: Organize your WebElement interactions into reusable methods. This reduces code duplication, improves readability, and makes maintenance easier as your test suite grows.

The WebElement class in Selenium WebDriver provides a wide array of methods that allow you to interact with HTML elements effectively. By using these commands, you can perform user actions, such as clicking buttons, entering text, retrieving information, and verifying element states.


Article Tags :

Similar Reads