Typing the Enter/Return key in Selenium
Asked Answered
L

30

347

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?

Lacee answered 27/10, 2009 at 6:32 Comment(5)
This might help asynchrony.blogspot.com/2008/11/…Julieannjulien
@croixhaug: What are you using? Selenium RC or WebDriver (Selenium 2)? What about language? Java? C#? or what?Moorwort
@RiponAlWasim, in 2009 (when the question was asked) there were no WebDriver. Also the answers for both have been here for a while...Ascensive
@AlexOkrushko: yes, you are rightMoorwort
This post is being discussed on meta.Galileo
R
359
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

Rohde answered 18/8, 2011 at 10:19 Comment(8)
I believe that it's moved. from selenium.webdriver.common.keys import Keys (#5503989)Isostasy
@HJames Broadhead: I have checked it, the Keys class for the actual JAVA (2.17.0) is still org.openqa.selenium.KeysRohde
WebElement.sendKeys(Keys.RETURN); this code is perfect for WebDriver (not for Selenium RC). More details example for google search: driver.findElement(By.id("gbqfq")).clear(); driver.findElement(By.id("gbqfq")).sendKeys("Ripon Al Wasim"); driver.findElement(By.id("gbqfq")).sendKeys(Keys.RETURN);Moorwort
I know that return is different than enter, but how is Keys.ENTER different? (I would think that Keys.RETURN would simply make it more obvious that it is a bot doing the action?)Stockade
@NoBrainer: Quick look at imported file will answer your question: RETURN = '\ue006' ENTER = '\ue007'. But why? Some relic or OS differences.Solfa
@NoBrainer: Enter and Return are different keys, have a look at the image of this wikipedia article: en.wikipedia.org/wiki/Enter_keyRohde
@Rohde Thanks for your solution. It's worthy for upvote.Fishworm
for python: from selenium.webdriver.common.keys import Keys password_field.send_keys(Keys.ENTER)Putto
E
260

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);
Endosmosis answered 28/2, 2014 at 9:37 Comment(1)
For Python, I found that appending "\n" to the input string is the most straightforward way to go. It worked in a search field.Tapp
B
44

You can use either of Keys.ENTER or Keys.RETURN. Here are the 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

Boob answered 15/12, 2017 at 10:10 Comment(0)
B
29

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")
Bursar answered 11/4, 2011 at 17:17 Comment(1)
Or more generally, values from Keys (import can be selenium.webdriver.common.keys import Keys), Keys.RETURN in this case.Amenable
V
16

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

Varico answered 26/2, 2019 at 4:43 Comment(0)
C
12

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}
Compunction answered 27/1, 2014 at 22:54 Comment(2)
What 'language'/context? Bash (command line)? Linux? Can you add some context to your answer?Amenable
It's for HTML tests suitesCompunction
A
9
selenium.keyPress("css=input.tagit-input.ui-autocomplete-input", "13");
Agreement answered 27/10, 2009 at 18:26 Comment(0)
L
9

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);
Lindeberg answered 11/10, 2012 at 8:32 Comment(2)
just out of curiosity , why do you prefer writing 3 lines of code which you can write in a single lineRounce
Isn't an "import" of sorts needed for Keys? In Python, it would be "from selenium.webdriver.common.keys import Keys".Amenable
T
7

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;
};
Thurmanthurmann answered 17/5, 2013 at 11:15 Comment(0)
M
6

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();
Moorwort answered 7/4, 2015 at 9:48 Comment(0)
K
6

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

Knowhow answered 1/10, 2015 at 7:58 Comment(0)
J
6
search = browser.find_element_by_xpath("//*[@type='text']")
search.send_keys(u'\ue007')

#ENTER = u'\ue007'

Refer to Selenium's documentation 'Special Keys'.

Jesicajeske answered 18/1, 2016 at 7:52 Comment(2)
This answer work but accidently voted it down because I used the wrong number.Overactive
Can you link to the documentation?Amenable
V
5

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)

Visit answered 12/7, 2011 at 8:18 Comment(1)
This is also true for a GWT input text field.Halutz
T
4

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);
Threefold answered 27/11, 2013 at 10:42 Comment(2)
If the element has ID, it is better to use ID instead of xpathMoorwort
What language? Isn't an "import" of sorts needed for Keys? In Python, it would be "from selenium.webdriver.common.keys import Keys".Amenable
C
4

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
Chestonchest answered 28/2, 2019 at 9:43 Comment(0)
R
3

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);
Remonaremonetize answered 28/5, 2015 at 12:17 Comment(1)
Could you please elaborate more your answer adding a little more description about the solution you provide?Bruce
F
3

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.

Fishworm answered 22/8, 2016 at 11:49 Comment(2)
What list? Can you link to it?Amenable
What language? Python?Amenable
M
3

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);
Macaco answered 7/11, 2016 at 11:43 Comment(0)
S
3
object.sendKeys("your message", Keys.ENTER);

It works.

Sensillum answered 4/9, 2017 at 11:3 Comment(0)
D
3

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);
Dodiedodo answered 10/11, 2017 at 9:49 Comment(1)
Can you link to documentation for the Robot class?Amenable
L
3

If you just want to press the Enter key (python):

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

ActionChains(driver).send_keys(Keys.ENTER).perform()
Literator answered 24/5, 2021 at 4:30 Comment(1)
this answer works perfectly driver.find_element_by_xpath('//xpath').send_keys(Keys.ENTER) in case for search works perfectly.Luthern
I
2

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();
Intervocalic answered 1/10, 2013 at 6:32 Comment(1)
Isn't an "import" of sorts needed for Keys? In Python, it would be "from selenium.webdriver.common.keys import Keys".Amenable
J
2

You can try:

selenium.keyPress("id="", "\\13");
Jerol answered 22/1, 2014 at 9:51 Comment(0)
C
2

For Ruby:

driver.find_element(:id, "XYZ").send_keys:return
Crews answered 11/4, 2014 at 22:15 Comment(0)
M
2

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);
Morell answered 7/4, 2015 at 10:26 Comment(0)
G
2

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
Graz answered 20/4, 2015 at 6:6 Comment(1)
Re "keys function": Do you mean send_keys() (this is about Python)?Amenable
T
2

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();
Terpineol answered 12/5, 2015 at 9:7 Comment(1)
Is "webElement" literal?Amenable
G
2

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);
}
Germaun answered 29/10, 2016 at 20:39 Comment(0)
Q
2
Actions action = new Actions(driver);
action.sendKeys(Keys.RETURN);
Quindecennial answered 6/1, 2017 at 16:42 Comment(1)
What language? Java?Amenable
C
1

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

driver.findElement(By.xpath('xpath')).sendKeys('ENTER');
Cerebrospinal answered 14/1, 2019 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.