Selenium Element Interactions
Once Selenium locates an element, it needs commands to act on that element. These commands mimic a real user typing, clicking, and reading text on a page.
Diagram: Interaction Flow
Locate Element
|
v
Perform Action (click, sendKeys, clear)
|
v
Read Result (getText, isDisplayed)
click()
Clicks a button, link, checkbox, or any clickable element.
WebElement loginButton = driver.findElement(By.id("login-btn"));
loginButton.click();
sendKeys()
Types text into an input field or text area.
WebElement emailField = driver.findElement(By.id("email"));
emailField.sendKeys("student@estudy247.com");
clear()
Removes existing text from an input field before typing new text.
emailField.clear();
emailField.sendKeys("newuser@estudy247.com");
Skipping clear() often appends new text to old text, creating an invalid value.
getText()
Reads the visible text inside an element, useful for checking messages or labels.
WebElement message = driver.findElement(By.id("welcome-msg"));
String text = message.getText();
System.out.println(text);
getAttribute()
Reads the value of a specific HTML attribute, like href, value, or class.
WebElement link = driver.findElement(By.id("home-link"));
String url = link.getAttribute("href");
isDisplayed(), isEnabled(), isSelected()
isDisplayed()
Returns true if an element is visible on the page.
isEnabled()
Returns true if an element accepts user interaction, useful for checking disabled buttons.
isSelected()
Returns true if a checkbox or radio button is currently checked.
WebElement checkbox = driver.findElement(By.id("agree-terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
This script checks a terms and conditions box only if it starts unchecked, avoiding an accidental un-check.
submit()
Submits a form directly, similar to pressing Enter inside a text field.
WebElement searchForm = driver.findElement(By.id("search-form"));
searchForm.submit();
Practical Example: A Login Flow
driver.get("https://www.estudy247.com/login");
driver.findElement(By.id("email")).sendKeys("student@estudy247.com");
driver.findElement(By.id("password")).sendKeys("mypassword");
driver.findElement(By.id("login-btn")).click();
String welcomeText = driver.findElement(By.id("welcome-msg")).getText();
System.out.println(welcomeText);
This script fills a login form, submits it, and reads the welcome message that confirms a successful login.
