ScreenshotNeo

BlogHow-to

How to Use Selenium sendKeys to Enter Text

Learn how to enter text with Selenium in Java, Python, JavaScript, and more, handle common failures, and choose the right keyboard interaction.

By the ScreenshotNeo team4 October 20267 min read

To enter text with Selenium, locate an editable element and call its element-level keyboard method: Java uses sendKeys("text"), while Python uses send_keys("text"). The target must be keyboard-interactable. Selenium scrolls elements into view and checks that they can be interacted with before performing the action. Selenium’s element interaction guide describes these checks.

Java: enter text and submit a form

This runnable example follows Selenium’s official first-script flow. It opens a page, locates a text box by name, types a value, submits the form, and reads the result. Use the locator that matches the page you are automating.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class EnterText {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.selenium.dev/selenium/web/web-form.html");

            WebElement textBox = driver.findElement(By.name("my-text"));
            textBox.sendKeys("Selenium");
            driver.findElement(By.cssSelector("button")).click();

            String message = driver.findElement(By.id("message")).getText();
            System.out.println(message);
        } finally {
            driver.quit();
        }
    }
}

The example assumes a compatible Selenium Java dependency and browser driver setup in the environment. See the official first Selenium script for language setup details.

Python: enter text and submit a form

Python spells the method send_keys. This complete script uses Selenium Manager through the normal driver constructor in current Selenium installations.

from selenium import webdriver
from selenium.webdriver.common.by import By

with webdriver.Chrome() as driver:
    driver.get("https://www.selenium.dev/selenium/web/web-form.html")

    text_box = driver.find_element(by=By.NAME, value="my-text")
    text_box.send_keys("Selenium")
    driver.find_element(by=By.CSS_SELECTOR, value="button").click()

    message = driver.find_element(by=By.ID, value="message").text
    print(message)

Install Selenium in the Python environment with pip install selenium. The page and selectors are from Selenium’s official first-script example.

JavaScript: locate an element and send keys

The JavaScript binding uses sendKeys on a WebElement. This Node.js example uses Selenium’s JavaScript package and the same demonstration form.

const { Builder, By } = require('selenium-webdriver');

(async function enterText() {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
    const textBox = await driver.findElement(By.name('my-text'));
    await textBox.sendKeys('Selenium');
    await driver.findElement(By.css('button')).click();
    const message = await driver.findElement(By.id('message')).getText();
    console.log(message);
  } finally {
    await driver.quit();
  }
})();

Install the binding with npm install selenium-webdriver. The JavaScript API documents WebElement.sendKeys and its key-sequence behavior.

Choose the right way to type

Need Use Notes
Enter ordinary text in a known field Element sendKeys / send_keys Locate the editable element, then send the string.
Interleave typing with pointer or keyboard actions Actions API Useful for a sequence of actions; its key behavior is not exactly the same as the element method.
Upload a file Send the file path to an <input type="file"> For remote sessions, the path must be available to the browser machine or transferred using a file detector.

Selenium’s keyboard actions guide explains Actions API typing. The JavaScript API reference covers modifier keys and file input paths.

Keyboard input with Actions API

Use an action sequence when typing is part of a larger keyboard workflow. The exact builder syntax differs by language binding; consult the official binding API. The Actions API’s sendKeys convenience action combines key-down and key-up behavior.

Special keys and modifiers

Element sendKeys accepts key sequences, including Selenium’s special key constants. In JavaScript, modifier keys such as Control, Shift, Alt, and Meta remain active until toggled, released with Key.NULL, or the sequence ends. For ordinary text, pass a string; use key constants only when the workflow needs a key press such as Enter or Tab.

Locate the correct editable element

The method acts on a WebElement, not a locator or the entire page. Common locator choices include an accessible name, stable ID, name attribute, or CSS selector. Prefer selectors tied to stable page semantics instead of brittle positional selectors.

// Java examples
WebElement byId = driver.findElement(By.id("email"));
WebElement byName = driver.findElement(By.name("email"));
WebElement byCss = driver.findElement(By.cssSelector("input[type='email']"));
byId.sendKeys("person@example.com");

For a rich text editor, the editable target may be an element with contenteditable. A visible wrapper around an editor is not necessarily the keyboard-interactable element, so inspect the page structure and locate the actual editable node.

Clear, replace, append, and submit

  • Append: calling sendKeys on a field with existing text normally types at the current caret position. Click or focus the field first if the caret position matters.
  • Replace: call clear() before sending the new value when the field supports clearing. For custom widgets, select existing text with keyboard actions if clearing is unsupported.
  • Submit: click the actual submit control or use the form’s supported keyboard behavior. Waiting for a result is more reliable than assuming the click completed a navigation.
  • Multiline text: use a textarea or contenteditable target. A standard single-line input may reject or normalize line breaks.
WebElement field = driver.findElement(By.name("email"));
field.clear();
field.sendKeys("person@example.com");
// Then click the form's submit control, or use the page's intended submission action.

Wait for the field when the page is dynamic

If a field appears after JavaScript runs, wait for it to be present and interactable instead of immediately looking it up. An explicit wait makes the reason for waiting clear and avoids fixed delays.

import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement field = wait.until(ExpectedConditions.elementToBeClickable(By.name("my-text")));
field.sendKeys("Selenium");

Choose a timeout that matches the application and test environment. If the wait expires, investigate whether the selector is correct, the element is inside a frame, or the page has not reached the expected state.

Common errors and fixes

Error or symptom Likely cause Fix
InvalidElementStateException The element is not editable or keyboard-interactable, such as a disabled or read-only control. Locate the actual editable field, and confirm it is enabled and writable before typing.
NoSuchElementException The locator does not match, or the field has not rendered yet. Inspect the live DOM, correct the locator, and use an explicit wait for dynamic content.
Text goes into the wrong place The locator matched a hidden duplicate or a different field. Use a more specific stable locator and verify the matched element and its attributes.
Text is missing or incomplete The app rerendered the field, validation transformed input, or typing began before it was ready. Wait for the field to be interactable, then check its value and application state after entry.
Element click intercepted or not interactable An overlay, animation, or layout state prevents interaction. Wait for the overlay or transition to finish and target the visible control. Selenium scrolls into view, but it cannot make an obstructed control usable.
File path fails on a remote browser The path exists on the test client but not the remote browser machine. Use a file detector to transfer the local file or provide a path accessible to the remote machine.

Performance and reliability

sendKeys is a direct browser interaction and is usually preferable to scripts that mutate the DOM value, because Selenium’s element interactions are designed to emulate user actions and validate interactability. Keep locators stable, wait on application conditions, and avoid arbitrary sleeps. For large text blocks, validate that the target control accepts the content and that the application processes it as expected.

Reliability also depends on focus, frame context, overlays, and application rerenders. If the field is in an iframe, switch into that frame before locating it; switch back to the default content afterward. After typing, assert the field value or a meaningful page result rather than treating the absence of an exception as proof of success.

Or skip the browser setup

If the goal is to capture the page after your automation, ScreenshotNeo is a website screenshot API and MCP server. Instead of managing a browser just to produce an image, make one request. See the ScreenshotNeo API documentation for options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners are accepted and removed before capture, along with known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server lets AI agents use screenshot, page-info, and PDF tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free account and get 1,000 screenshots a month with no card.

FAQ

Is it sendKeys or send_keys?

Java uses sendKeys; Python uses send_keys. Other bindings follow their own naming conventions.

Can I type into a contenteditable element?

Yes, if you locate the keyboard-interactable editable element itself.

Can Selenium send a file through a file input?

Yes. Send the path to the file input. In remote sessions, make sure the file path is available to the browser or use a file detector.

Should I use Actions or the element method?

Use the element method for text in a specific field. Use Actions when keyboard input must be sequenced with other actions.