Selenium provides the sendKeys() method to type text into input fields. Using this method, we can send text directly to a web element identified by Selenium.
Below, we have provided example scripts that demonstrate how to enter text into an input box using Selenium in Java, C#, and JavaScript.
sendKeys in Selenium
-
Java
-
C#
-
JavaScript
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class SendKeysExample {
@Test
public void inputText() {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement inputBox = driver.findElement(By.id("username"));
inputBox.sendKeys("TestUser");
driver.quit();
}
}
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
namespace SeleniumExamples
{
public class SendKeysExample
{
[Test]
public void InputText()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://example.com");
IWebElement inputBox = driver.FindElement(By.Id("username"));
inputBox.SendKeys("TestUser");
driver.Quit();
}
}
}
const { Builder, By } = require("selenium-webdriver");
(async function sendKeysExample() {
let driver = await new Builder().forBrowser("chrome").build();
await driver.get("https://example.com");
let inputBox = await driver.findElement(By.id("username"));
await inputBox.sendKeys("TestUser");
await driver.quit();
})();