Series Navigation
← Part 4: Locators — ID, Name, XPath, CSS and Beyond
→ Part 6: Waits — Implicit, Explicit and Fluent
Basic WebElement Methods
Every element found by driver.findElement() returns a WebElement. Here are all its methods:
WebElement element = driver.findElement(By.id("myElement"));
// Interactions
element.click(); // click the element
element.sendKeys("text"); // type text into input
element.clear(); // clear input field
element.submit(); // submit the form this element belongs to
// Reading element data
String text = element.getText(); // visible text
String attribute = element.getAttribute("href"); // any HTML attribute
String cssValue = element.getCssValue("color"); // CSS property value
String tagName = element.getTagName(); // "input", "button", etc.
// Element state
boolean isDisplayed = element.isDisplayed(); // visible on page
boolean isEnabled = element.isEnabled(); // not disabled
boolean isSelected = element.isSelected(); // checkbox/radio checked
// Location and size
Point location = element.getLocation(); // x,y coordinates on page
Dimension size = element.getSize(); // width, height
Rectangle rect = element.getRect(); // location + size combined
Text Input Fields
WebElement searchBox = driver.findElement(By.id("search"));
// Type text
searchBox.sendKeys("Selenium WebDriver");
// Clear existing text then type
searchBox.clear();
searchBox.sendKeys("New search term");
// Type and press Enter
searchBox.sendKeys("query" + Keys.RETURN);
// Keys.RETURN and Keys.ENTER both work
// Type Tab to move to next field
searchBox.sendKeys(Keys.TAB);
// Type with modifier keys
searchBox.sendKeys(Keys.chord(Keys.CONTROL, "a")); // Ctrl+A (select all)
searchBox.sendKeys(Keys.chord(Keys.CONTROL, "c")); // Ctrl+C (copy)
searchBox.sendKeys(Keys.chord(Keys.CONTROL, "v")); // Ctrl+V (paste)
// Special keys
searchBox.sendKeys(Keys.BACK_SPACE); // delete one character
searchBox.sendKeys(Keys.DELETE); // delete key
searchBox.sendKeys(Keys.ESCAPE); // escape
searchBox.sendKeys(Keys.PAGE_DOWN); // scroll down
searchBox.sendKeys(Keys.HOME); // go to start of line
searchBox.sendKeys(Keys.END); // go to end of line
searchBox.sendKeys(Keys.F5); // F5 key
Clicking Elements
WebElement button = driver.findElement(By.id("submitBtn"));
// Standard click
button.click();
// Sometimes click() fails because element is behind another element
// Use JavaScript click as fallback
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", button);
// Right-click (context menu)
Actions actions = new Actions(driver);
actions.contextClick(button).perform();
// Double-click
actions.doubleClick(button).perform();
// Click and hold
actions.clickAndHold(button).perform();
actions.release().perform();
Dropdown Menus — The Select Class
For standard HTML <select> elements, use the Select wrapper class:
<select id="country" name="country">
<option value="">-- Select Country --</option>
<option value="US">United States</option>
<option value="IN">India</option>
<option value="UK">United Kingdom</option>
<option value="CA">Canada</option>
</select>
import org.openqa.selenium.support.ui.Select;
WebElement dropdownElement = driver.findElement(By.id("country"));
Select dropdown = new Select(dropdownElement);
// Select by visible text
dropdown.selectByVisibleText("India");
// Select by value attribute
dropdown.selectByValue("IN");
// Select by index (0-based)
dropdown.selectByIndex(2);
// Get current selection
WebElement selected = dropdown.getFirstSelectedOption();
System.out.println("Selected: " + selected.getText()); // India
// Get all options
List<WebElement> allOptions = dropdown.getOptions();
allOptions.forEach(opt -> System.out.println(opt.getText()));
// For multi-select dropdowns
dropdown.selectByVisibleText("India");
dropdown.selectByVisibleText("United States");
List<WebElement> allSelected = dropdown.getAllSelectedOptions();
// Deselect (only for multi-select)
dropdown.deselectByVisibleText("India");
dropdown.deselectAll();
// Check if multi-select
boolean isMultiple = dropdown.isMultiple();
Custom Dropdowns (Not <select>)
Modern UIs often use custom dropdown components built with divs:
<div class="custom-dropdown" id="roleDropdown">
<div class="selected-value">Select Role</div>
<ul class="dropdown-options" style="display:none">
<li data-value="admin">Administrator</li>
<li data-value="user">Standard User</li>
<li data-value="viewer">Viewer</li>
</ul>
</div>
// Click to open the dropdown
driver.findElement(By.cssSelector("#roleDropdown .selected-value")).click();
// Wait for options to appear (Part 6 covers waits properly)
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("#roleDropdown .dropdown-options")
));
// Click the desired option
driver.findElement(By.cssSelector(
"#roleDropdown li[data-value='admin']"
)).click();
Checkboxes and Radio Buttons
<input type="checkbox" id="rememberMe" name="remember">
<label for="rememberMe">Remember Me</label>
<input type="checkbox" id="newsletter" name="newsletter" checked>
<label for="newsletter">Subscribe to newsletter</label>
<input type="radio" id="male" name="gender" value="male">
<input type="radio" id="female" name="gender" value="female">
WebElement rememberMe = driver.findElement(By.id("rememberMe"));
WebElement newsletter = driver.findElement(By.id("newsletter"));
// Check a checkbox (if not already checked)
if (!rememberMe.isSelected()) {
rememberMe.click();
}
System.out.println("Checked: " + rememberMe.isSelected()); // true
// Uncheck a checkbox
if (newsletter.isSelected()) {
newsletter.click();
}
// Radio buttons
WebElement maleRadio = driver.findElement(By.id("male"));
maleRadio.click(); // select male
// Verify radio is selected
Assert.assertTrue(maleRadio.isSelected(), "Male should be selected");
Assert.assertFalse(
driver.findElement(By.id("female")).isSelected(),
"Female should not be selected"
);
File Upload
<input type="file" id="fileUpload" accept=".pdf,.doc">
WebElement fileInput = driver.findElement(By.id("fileUpload"));
// Provide absolute file path — DO NOT click() the element first
String filePath = System.getProperty("user.dir") + "/src/test/resources/test-document.pdf";
fileInput.sendKeys(filePath);
// For multiple files
fileInput.sendKeys(filePath1 + "\n" + filePath2);
// Verify file name appears in UI after upload
WebElement fileName = driver.findElement(By.cssSelector(".file-name"));
Assert.assertEquals(fileName.getText(), "test-document.pdf");
Reading Element Information
// Text content
WebElement heading = driver.findElement(By.tagName("h1"));
String text = heading.getText();
// getText() returns visible text only, strips HTML tags
// HTML attributes
WebElement link = driver.findElement(By.cssSelector("a.profile-link"));
String href = link.getAttribute("href");
String title = link.getAttribute("title");
String cls = link.getAttribute("class");
// Input values
WebElement input = driver.findElement(By.id("email"));
String currentValue = input.getAttribute("value"); // what's typed in the field
// Note: getText() on input returns empty — use getAttribute("value")
// CSS properties
WebElement errorMsg = driver.findElement(By.id("error"));
String color = errorMsg.getCssValue("color"); // rgb(255, 0, 0)
String display = errorMsg.getCssValue("display"); // none / block
String fontWeight = errorMsg.getCssValue("font-weight"); // 700
// Element dimensions and position
Dimension dim = errorMsg.getSize();
System.out.println("Width: " + dim.width + ", Height: " + dim.height);
Point loc = errorMsg.getLocation();
System.out.println("X: " + loc.x + ", Y: " + loc.y);
Real-World Example: Complete Login Test
@Test
public void testSuccessfulLogin() {
WebDriver driver = getDriver();
driver.get("https://the-internet.herokuapp.com/login");
// Enter credentials
driver.findElement(By.id("username")).sendKeys("tomsmith");
driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
driver.findElement(By.cssSelector("button[type='submit']")).click();
// Verify redirect to secure area
Assert.assertTrue(driver.getCurrentUrl().contains("/secure"),
"Should redirect to secure page");
// Verify success message
WebElement flashMsg = driver.findElement(By.id("flash"));
Assert.assertTrue(flashMsg.getText().contains("You logged into a secure area!"),
"Success message should appear");
// Logout
driver.findElement(By.cssSelector("a.button.secondary")).click();
Assert.assertTrue(driver.getCurrentUrl().contains("/login"),
"Should redirect back to login");
}
@Test
public void testFailedLogin() {
WebDriver driver = getDriver();
driver.get("https://the-internet.herokuapp.com/login");
driver.findElement(By.id("username")).sendKeys("wronguser");
driver.findElement(By.id("password")).sendKeys("wrongpassword");
driver.findElement(By.cssSelector("button[type='submit']")).click();
// Verify error message
WebElement error = driver.findElement(By.id("flash"));
Assert.assertTrue(error.getText().contains("Your username is invalid!"),
"Error message should appear for invalid credentials");
Assert.assertTrue(error.isDisplayed(), "Error must be visible");
}
What's Next
In Part 6 we tackle the most common cause of flaky tests — timing. You'll learn the difference between implicit waits, explicit waits, and fluent waits, and which to use in which situation.
Discussion
Loading...Leave a Comment
All comments are reviewed before appearing. No links please.