How To Press Keyboard Keys in Selenium?

The Problem

On occasion you’ll come across functionality that requires the use of keyboard key presses in your tests. Perhaps you’ll need to tab to traverse from one portion of the page to another, back out of some kind of menu or overlay with the escape key, or even submit a form with Enter.

But how do you do it and where do you start?

A Solution

You can easily issue a key press by using the send_keys command.

driver.findElement(By.id(“content”)).sendKeys(Keys.SPACE);

Alternatively, you can also issue a key press without finding the element first,

Actions builder = new Actions(driver);
builder.sendKeys(Keys.LEFT).build().perform();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s