sendKeys()
The sendKeys() method is used to enter text or key sequences into an input-capable element (text fields, textareas, password fields). It simulates real keyboard input through the browser, making it fundamental to form automation in Selenium.
1. What sendKeys() Does
Definition:
sendKeys() types characters as if a user is pressing keys on the keyboard into the target WebElement.
Internally, Selenium:
- Verifies the element is present and interactable
- Focuses the element
- Dispatches keyboard events to the browser
2. Preconditions for Successful sendKeys()
For reliable input, all must be true:
- Element is present in the DOM
- Element is visible
- Element is enabled
- Element accepts text input
- Correct window/frame context is active
If any condition fails, Selenium throws an exception.
3. Common Elements Used with sendKeys()
- Text inputs (<input type="text">)
- Password fields
- Email/number inputs
- Textareas
- Search fields
- File inputs (special case—file upload)
4. What sendKeys() Does NOT Do
- Does not clear existing text automatically
- Does not wait for the element to be ready
- Does not validate the entered value
- Does not submit forms (unless combined with ENTER)
Synchronization and validation are your responsibility.
5. Clearing Text Before Typing (Best Practice)
Most real inputs already contain text (defaults, autofill, cached values).
Recommended pattern:
- Ensure visibility
- Clear the field
- Then type
This avoids concatenated or corrupted input.
6. Sending Special Keys (Keyboard Actions)
sendKeys() can send keyboard keys such as:
- ENTER / RETURN (submit forms)
- TAB (move focus)
- BACKSPACE / DELETE
- CTRL / ALT combinations (platform dependent)
Use cases:
- Submitting forms without clicking
- Navigating between fields
- Clearing content with shortcuts
7. Handling Dynamic Inputs & Masks
Modern UIs often use:
- Input masks (phone, currency)
- Auto-formatting
- Validation on keypress
Implications:
- Typing speed and sequence matter
- Sometimes requires pauses or explicit waits
- Validation may trigger mid-typing
Best practice: Validate final value after input.
8. Common Exceptions with sendKeys()
ElementNotInteractableException
- Field exists but is hidden/disabled
- Fix: Wait for visibility and enabled state.
InvalidElementStateException
- Element does not accept text
- Fix: Verify element type and state.
StaleElementReferenceException
- DOM refreshed after locating element
- Fix: Re-locate element before typing.
TimeoutException
- Element never becomes ready
- Fix: Verify locator and waits.
9. File Upload with sendKeys() (Special Case)
For file inputs:
- sendKeys() sets the absolute file path
- No OS dialog interaction required
Constraints:
- Works only with <input type="file">
- Path must exist on the execution machine (CI included)
This is the preferred file upload approach in Selenium.
10. sendKeys() vs JavaScript Value Set (Conceptual)
- sendKeys(): Triggers real keyboard events (preferred)
- JavaScript set value: Bypasses events (use only as fallback)
Rule: Use sendKeys() first to mimic user behavior accurately.
11. Page Object Model (POM) Usage
In frameworks:
- sendKeys() is wrapped inside page methods
- Tests call semantic actions (e.g., enterUsername())
This improves:
- Readability
- Reusability
- Maintenance
12. Common Beginner Mistakes
- Typing without clearing existing text
- Using Thread.sleep() instead of waits
- Typing into hidden fields
- Ignoring input masks and validations
- Using JavaScript input prematurely
13. Interview Perspective
Short Answer:
sendKeys() is used to enter text or keyboard inputs into a WebElement, simulating real user typing.
Real-Time Answer:
In Selenium, sendKeys() sends keyboard input to a visible and enabled element, triggering native key events. It does not clear existing text or wait automatically, so proper synchronization and validation are required.
14. Key Takeaway
- sendKeys() simulates real typing
- Clear fields explicitly when needed
- Synchronize before typing
- Validate the final value
- Prefer sendKeys() over JavaScript input
Stable input automation depends more on timing and validation than on typing itself.
15. Practical sendKeys() Examples (Interview Ready)
1. Basic sendKeys() Usage
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
Key Point: Types text into input or textarea.
2. sendKeys() with clear()
WebElement input = driver.findElement(By.name("search"));
input.clear();
input.sendKeys("Selenium WebDriver");
Best Practice: Always clear before typing.
3. sendKeys() with Multiple Values
WebElement input = driver.findElement(By.id("firstName"));
input.sendKeys("John", " ", "Doe");
Note: Accepts varargs.
4. sendKeys() with Keyboard Keys
import org.openqa.selenium.Keys;
WebElement input = driver.findElement(By.id("search"));
input.sendKeys("Selenium", Keys.ENTER);
5. Using Special Keys (TAB)
input.sendKeys("admin", Keys.TAB, "password");
Use Case: Simulate real keyboard navigation.
6. sendKeys() to Upload a File
WebElement upload = driver.findElement(By.id("fileUpload"));
upload.sendKeys("C:\\files\\resume.pdf");
Interview Favorite: No AutoIT required.
7. sendKeys() with Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement email =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));
email.sendKeys("test@example.com");
8. sendKeys() After Scrolling Into View
WebElement input = driver.findElement(By.id("comments"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", input);
input.sendKeys("Feedback text");
9. sendKeys() on Disabled Element (❌ Fails)
driver.findElement(By.id("disabledField"))
.sendKeys("text"); // ❌
Fix:
- Enable element first
- Or remove disabled via JS (if allowed)
10. sendKeys() Using JavaScript (Last Resort)
WebElement input = driver.findElement(By.id("username"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value='admin';", input);
11. sendKeys() with Dynamic Input
String value = "User_" + System.currentTimeMillis();
driver.findElement(By.id("user")).sendKeys(value);
12. sendKeys() After Page Refresh (Stale Fix)
WebElement input = driver.findElement(By.id("email"));
driver.navigate().refresh();
// input.sendKeys("x"); ❌ stale
input = driver.findElement(By.id("email"));
input.sendKeys("test@example.com");
13. sendKeys() Inside Frame
driver.switchTo().frame("loginFrame");
driver.findElement(By.id("user")).sendKeys("admin");
driver.switchTo().defaultContent();
14. sendKeys() with Actions Class
Actions actions = new Actions(driver);
WebElement input = driver.findElement(By.id("search"));
actions.sendKeys(input, "Selenium").perform();
Use Case: Complex keyboard interactions.
15. sendKeys() with CTRL + A (Select All)
input.sendKeys(Keys.CONTROL, "a");
16. Clear Using Keyboard
input.sendKeys(Keys.CONTROL, "a", Keys.DELETE);
Alternative to: input.clear().
17. sendKeys() Validation Using getAttribute()
WebElement input = driver.findElement(By.id("email"));
input.sendKeys("test@example.com");
Assert.assertEquals(
input.getAttribute("value"),
"test@example.com"
);
18. Loop with sendKeys() (Data Driven)
String[] users = {"admin", "guest", "test"};
for (String user : users) {
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys(user);
}
19. ❌ Common Interview Mistake
driver.sendKeys("text"); // ❌ invalid
Correct:
driver.findElement(By.id("x")).sendKeys("text"); // ✅
20. sendKeys() in Page Object Model (POM)
@FindBy(id = "username")
WebElement username;
public void enterUsername(String value) {
username.clear();
username.sendKeys(value);
}
21. sendKeys() with Soft Assertions
SoftAssert soft = new SoftAssert();
input.sendKeys("data");
soft.assertEquals(input.getAttribute("value"), "data");
soft.assertAll();
22. sendKeys() After Element Enabled Check
WebElement input = driver.findElement(By.id("email"));
if (input.isEnabled()) {
input.sendKeys("test@example.com");
}
23. Handling Auto-Suggest Input
WebElement search = driver.findElement(By.id("search"));
search.sendKeys("Selenium");
Thread.sleep(1000);
search.sendKeys(Keys.ARROW_DOWN, Keys.ENTER);
24. sendKeys() vs setValue() (Interview)
- sendKeys() → simulates real typing
- JS value set → bypasses UI events
25. Interview Summary – sendKeys() in Selenium
element.sendKeys();
Key Points:
- Works on input & textarea
- Supports special keys
- Used for file upload
- Use waits for stability
- JS sendKeys is last resort