[selenium] Typing the Enter/Return key using Python and Selenium

I'm looking for a quick way to type the Enter or Return key in Selenium.

Unfortunately, the form I'm trying to test (not my own code, so I can't modify) doesn't have a Submit button. When working with it manually, I just type Enter or Return. How can I do that with the Selenium type command as there is no button to click?

This question is related to selenium automation automated-tests keypress enter

The answer is


selenium.keyPress("css=input.tagit-input.ui-autocomplete-input", "13");

driver.findElement(By.id("Value")).sendKeys(Keys.RETURN); or driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);


You can use either of Keys.ENTER or Keys.RETURN. Here are some details:

Usage:

  • Java:

  • Using Keys.ENTER:

         import org.openqa.selenium.Keys;
         driver.findElement(By.id("element_id")).sendKeys(Keys.ENTER);
    
  • Using Keys.RETURN

         import org.openqa.selenium.Keys;
         driver.findElement(By.id("element_id")).sendKeys(Keys.RETURN);
    
  • Python:

  • Using Keys.ENTER:

         from selenium.webdriver.common.keys import Keys
         driver.find_element_by_id("element_id").send_keys(Keys.ENTER)
    
  • Using Keys.RETURN

         from selenium.webdriver.common.keys import Keys
         driver.find_element_by_id("element_id").send_keys(Keys.RETURN)
    

Keys.ENTER and Keys.RETURN both are from org.openqa.selenium.Keys, which extends java.lang.Enum<Keys> and implements java.lang.CharSequence


Enum Keys

Enum Keys is the representations of pressable keys that aren't text. These are stored in the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF.

Key Codes:

The special keys codes for them are as follows:

  • RETURN = u'\ue006'
  • ENTER = u'\ue007'

The implementation of all the Enum Keys are handled the same way.

Hence these is No Functional or Operational difference while working with either sendKeys(Keys.ENTER); or WebElement.sendKeys(Keys.RETURN); through Selenium.


Enter Key and Return Key

On computer keyboards, the Enter (or the Return on Mac OS X) in most cases causes a command line, window form, or dialog box to operate its default function. This is typically to finish an "entry" and begin the desired process and is usually an alternative to pressing an OK button.

The Return is often also referred as the Enter and they usually perform identical functions; however in some particular applications (mainly page layout) Return operates specifically like the Carriage Return key from which it originates. In contrast, the Enter is commonly labelled with its name in plain text on generic PC keyboards.


References


Java/JavaScript:

You could probably do it this way also, non-natively:

public void triggerButtonOnEnterKeyInTextField(String textFieldId, String clickableButId)
{
    ((JavascriptExecutor) driver).executeScript(
        "   elementId = arguments[0];
            buttonId = arguments[1];
            document.getElementById(elementId)
                .addEventListener("keyup", function(event) {
                    event.preventDefault();
                    if (event.keyCode == 13) {
                        document.getElementById(buttonId).click();
                    }
                });",

        textFieldId,
        clickableButId);
}

For Ruby:

driver.find_element(:id, "XYZ").send_keys:return

If you are looking for "how to press the Enter key from the keyboard in Selenium WebDriver (Java)",then below code will definitely help you.

// Assign a keyboard object
Keyboard keyboard = ((HasInputDevices) driver).getKeyboard();

// Enter a key
keyboard.pressKey(Keys.ENTER);

For everyone using JavaScript / Node.js, this worked for me:

driver.findElement(By.xpath('xpath')).sendKeys('ENTER');

You can try:

selenium.keyPress("id="", "\\13");

When you don't want to search any locator, you can use the Robot class. For example,

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Now that Selenium 2 has been released, it's a bit easier to send an Enter key, since you can do it with the send_keys method of the selenium.webdriver.remote.webelement.WebElement class (this example code is in Python, but the same method exists in Java):

>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/example/page")
>>> textbox = wd.find_element_by_css_selector("input")
>>> textbox.send_keys("Hello World\n")

When writing HTML tests, the ENTER key is available as ${KEY_ENTER}.

You can use it with sendKeys, here is an example:

sendKeys | id=search | ${KEY_ENTER}

To enter keys using Selenium, first you need to import the following library:

import org.openqa.selenium.Keys

then add this code where you want to enter the key

WebElement.sendKeys(Keys.RETURN);

You can replace RETURN with any key from the list according to your requirement.


Try to use an XPath expression for searching the element and then, the following code works:

driver.findElement(By.xpath(".//*[@id='txtFilterContentUnit']")).sendKeys(Keys.ENTER);

I had to send the Enter key in the middle of a text. So I passed the following text to send keys function to achieve 1\n2\n3:

1\N{U+E007}2\N{U+E007}3

search = browser.find_element_by_xpath("//*[@type='text']")
search.send_keys(u'\ue007')

#ENTER = u'\ue007'

Refer to Selenium's documentation 'Special Keys'.


It could be achieved using Action interface as well. In case of WebDriver -

WebElement username = driver.findElement(By.name("q"));
username.sendKeys(searchKey);
Actions action = new Actions(driver);
action.sendKeys(Keys.RETURN);
action.perform();

For Selenium WebDriver using XPath (if the key is visible):

driver.findElement(By.xpath("xpath of text field")).sendKeys(Keys.ENTER);

or,

driver.findElement(By.xpath("xpath of text field")).sendKeys(Keys.RETURN);

import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);

The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys


There are the following ways of pressing keys - C#:

Driver.FindElement(By.Id("Value")).SendKeys(Keys.Return);

OR

OpenQA.Selenium.Interactions.Actions action = new OpenQA.Selenium.Interactions.Actions(Driver);
action.SendKeys(OpenQA.Selenium.Keys.Escape);

OR

IWebElement body = GlobalDriver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Escape);

For Selenium Remote Control with Java:

selenium.keyPress("elementID", "\13");

For Selenium WebDriver (a.k.a. Selenium 2) with Java:

driver.findElement(By.id("elementID")).sendKeys(Keys.ENTER);

Or,

driver.findElement(By.id("elementID")).sendKeys(Keys.RETURN);

Another way to press Enter in WebDriver is by using the Actions class:

Actions action = new Actions(driver);
action.sendKeys(driver.findElement(By.id("elementID")), Keys.ENTER).build().perform();

You can call submit() on the element object in which you entered your text.

Alternatively, you can specifically send the Enter key to it as shown in this Python snippet:

from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.ENTER) # 'element' is the WebElement object corresponding to the input field on the page

I just like to note that I needed this for my Cucumber tests and found out that if you like to simulate pressing the enter/return key, you need to send the :return value and not the :enter value (see the values described here)


Java

driver.findElement(By.id("Value")).sendKeys(Keys.RETURN);

OR,

driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);

Python

from selenium.webdriver.common.keys import Keys
driver.find_element_by_name("Value").send_keys(Keys.RETURN)

OR,

driver.find_element_by_name("Value").send_keys(Keys.ENTER)

OR,

element = driver.find_element_by_id("Value")
element.send_keys("keysToSend")
element.submit()

Ruby

element = @driver.find_element(:name, "value")
element.send_keys "keysToSend"
element.submit

OR,

element = @driver.find_element(:name, "value")
element.send_keys "keysToSend"
element.send_keys:return

OR,

@driver.action.send_keys(:enter).perform
@driver.action.send_keys(:return).perform

C#

driver.FindElement(By.Id("Value")).SendKeys(Keys.Return);

OR,

driver.FindElement(By.Id("Value")).SendKeys(Keys.Enter);

If you are in this specific situation:

a) want to just press the key, but you not have a specific webElement to click on

b) you are using Selenium 2 (WebDriver)

Then the solution is:

    Actions builder = new Actions(webDriverInstance);
    builder.sendKeys(Keys.RETURN).perform();

For those folks who are using WebDriverJS Keys.RETURN would be referenced as

webdriver.Key.RETURN

A more complete example as a reference might be helpful too:

var pressEnterToSend = function () {
    var deferred = webdriver.promise.defer();
    webdriver.findElement(webdriver.By.id('id-of-input-element')).then(function (element) {
        element.sendKeys(webdriver.Key.RETURN);
        deferred.resolve();
    });

    return deferred.promise;
};

You just do this:

final private WebElement input = driver.findElement(By.id("myId"));
input.clear();
input.sendKeys(value); // The value we want to set to input
input.sendKeys(Keys.RETURN);

Actions action = new Actions(driver);
action.sendKeys(Keys.RETURN);

object.sendKeys("your message", Keys.ENTER);

It works.


In Python

Step 1. from selenium.webdriver.common.keys import Keys

Step 2. driver.find_element_by_name("").send_keys(Keys.ENTER)

Note: you have to write Keys.ENTER


Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to automation

element not interactable exception in selenium web automation Upload file to SFTP using PowerShell Check if element is clickable in Selenium Java Schedule automatic daily upload with FileZilla How can I start InternetExplorerDriver using Selenium WebDriver How to use Selenium with Python? Excel VBA Automation Error: The object invoked has disconnected from its clients How to type in textbox using Selenium WebDriver (Selenium 2) with Java? Sending email from Command-line via outlook without having to click send R command for setting working directory to source file location in Rstudio

Examples related to automated-tests

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout" Select a date from date picker using Selenium webdriver How can I scroll a web page using selenium webdriver in python? How to find specific lines in a table using Selenium? Debugging "Element is not clickable at point" error Running Selenium WebDriver python bindings in chrome Get HTML source of WebElement in Selenium WebDriver using Python Selenium C# WebDriver: Wait until element is present Random "Element is no longer attached to the DOM" StaleElementReferenceException Scroll Element into View with Selenium

Examples related to keypress

onKeyDown event not working on divs in React How can I listen for keypress event on the whole page? How to handle the `onKeyPress` event in ReactJS? detect key press in python? jQuery Keypress Arrow Keys Submit form on pressing Enter with AngularJS How to trigger an event in input text after I stop typing/writing? How to capture Enter key press? JQuery: detect change in input field Pressing Ctrl + A in Selenium WebDriver

Examples related to enter

Excel doesn't update value unless I hit Enter Press enter in textbox to and execute button command Submit form on pressing Enter with AngularJS How to insert a new line in strings in Android Enter triggers button click C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through? Typing the Enter/Return key using Python and Selenium How to detect pressing Enter on keyboard using jQuery? Prevent form submission on Enter key press