selenium_element_interaction
Selenium - Working with Elements
Section titled “Selenium - Working with Elements”Once you have located a WebElement using one of the locator strategies (findElement or findElements), you can perform various actions on it or retrieve information from it. Selenium WebDriver provides a rich set of methods for interacting with common web elements like text boxes, buttons, checkboxes, radio buttons, dropdowns, and more.
This section covers common interactions with standard HTML elements.
Common Element Interactions
Section titled “Common Element Interactions”Clicking Elements
Section titled “Clicking Elements”The most common action is clicking. This works on buttons, links, radio buttons, checkboxes, and sometimes other elements like divs or images if they have click handlers.
// Locate a submit button and click itWebElement submitButton = driver.findElement(By.id("submit-btn"));submitButton.click();
// Locate a link and click itWebElement profileLink = driver.findElement(By.linkText("My Profile"));profileLink.click();Typing Text (Input Fields and Textareas)
Section titled “Typing Text (Input Fields and Textareas)”Use the sendKeys() method to simulate typing into text input fields or textareas.
// Locate a username input fieldWebElement usernameInput = driver.findElement(By.name("username"));
// Type text into the fieldusernameInput.sendKeys("testuser");
// You can also send special keys// import org.openqa.selenium.Keys;// usernameInput.sendKeys(Keys.TAB); // Simulate pressing the Tab keyClearing Text
Section titled “Clearing Text”Use the clear() method to remove any existing text from an input field or textarea before typing new text.
WebElement searchBox = driver.findElement(By.id("search"));
// Clear any existing textsearchBox.clear();
// Enter a new search termsearchBox.sendKeys("Selenium WebDriver");Submitting Forms
Section titled “Submitting Forms”You can either click() the submit button directly, or if your focus is within a form element (like an input field), you can call the submit() method on that element. submit() finds the enclosing form and submits it.
WebElement passwordInput = driver.findElement(By.id("password"));passwordInput.sendKeys("secret");
// Option 1: Click the submit button (preferred if button exists)// WebElement loginButton = driver.findElement(By.id("login-button"));// loginButton.click();
// Option 2: Submit from an element within the formpasswordInput.submit();Working with Checkboxes and Radio Buttons
Section titled “Working with Checkboxes and Radio Buttons”You can click() them to select/deselect. You can also check their current state using isSelected().
// Locate a checkboxWebElement newsletterCheckbox = driver.findElement(By.id("subscribe-news"));
// Check if it's already selectedif (!newsletterCheckbox.isSelected()) { System.out.println("Checkbox not selected, clicking it..."); newsletterCheckbox.click();}
// Locate a radio buttonWebElement femaleRadioButton = driver.findElement(By.cssSelector("input[type='radio'][value='female']"));
// Select it if not already selectedif (!femaleRadioButton.isSelected()) { femaleRadioButton.click();}Working with Dropdown Lists (Select Elements)
Section titled “Working with Dropdown Lists (Select Elements)”For standard HTML <select> dropdowns, Selenium provides a dedicated Select class (in org.openqa.selenium.support.ui.Select) which simplifies interaction.
// Import the Select class// import org.openqa.selenium.support.ui.Select;
// Locate the <select> elementWebElement countryDropdownElement = driver.findElement(By.id("country"));
// Create a Select objectSelect countrySelect = new Select(countryDropdownElement);
// Select an option by its visible textcountrySelect.selectByVisibleText("Canada");
// Wait a bit to see the selection (replace with explicit wait in real tests)// try { Thread.sleep(2000); } catch (InterruptedException e) {}
// Select an option by its value attribute// Example: <option value="US">United States</option>countrySelect.selectByValue("US");
// Wait a bit// try { Thread.sleep(2000); } catch (InterruptedException e) {}
// Select an option by its index (0-based)countrySelect.selectByIndex(0); // Selects the first option
// Get the currently selected optionWebElement selectedOption = countrySelect.getFirstSelectedOption();System.out.println("Selected option: " + selectedOption.getText());
// Get all optionsjava.util.List<WebElement> allOptions = countrySelect.getOptions();System.out.println("Total options: " + allOptions.size());Note: If the dropdown is implemented using custom elements (like <div> and <ul>), you cannot use the Select class. You’ll need to click the element to open the dropdown and then click the desired option element using standard locators.
Getting Information from Elements
Section titled “Getting Information from Elements”Getting Text
Section titled “Getting Text”Use getText() to retrieve the visible text content of an element (what the user sees).
// Locate a paragraph or headingWebElement messageElement = driver.findElement(By.id("welcome-message"));String message = messageElement.getText();System.out.println("Welcome message: " + message);Getting Attributes
Section titled “Getting Attributes”Use getAttribute("attributeName") to get the value of a specific HTML attribute (like href, src, value, class, style).
// Locate a linkWebElement docsLink = driver.findElement(By.linkText("Documentation"));String linkUrl = docsLink.getAttribute("href");System.out.println("Docs link URL: " + linkUrl);
// Get the value typed into an input boxWebElement nameInput = driver.findElement(By.id("name"));nameInput.sendKeys("Test Name");String enteredValue = nameInput.getAttribute("value");System.out.println("Value in input: " + enteredValue);Checking Element State
Section titled “Checking Element State”You can check if an element is currently displayed, enabled, or selected.
WebElement loginButton = driver.findElement(By.id("login"));WebElement rememberMeCheckbox = driver.findElement(By.id("remember"));
// Is the button visible on the page?boolean isDisplayed = loginButton.isDisplayed();System.out.println("Login button displayed: " + isDisplayed);
// Is the button clickable?boolean isEnabled = loginButton.isEnabled();System.out.println("Login button enabled: " + isEnabled);
// Is the checkbox checked? (Returns false if not selected)boolean isSelected = rememberMeCheckbox.isSelected();System.out.println("Remember me selected: " + isSelected);These basic interactions form the core of most WebDriver scripts. Combining these with appropriate waits and assertions allows you to automate complex user workflows.