Selenium WebDriver - WebElement Commands Using Java
Last Updated :
26 Jul, 2025
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 OutputBest Practices of WebElement Commands
Follow best practices for using WebElement commands in Selenium WebDriver for easier automation:
- 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. - 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. - 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. - 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. - 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. - 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.
- 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.
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING