Select Page
Selenium Testing

Selenium Keys & Sendkeys Examples

Gaining enduring technical know-how of selenium basics to advanced level is a key to test automation success.

Selenium SendKeys
Listen to this blog

A major proportion of automation testers are familiar with Selenium Keys feature. You can use Selenium Keys and SendKeys in WebElement class, Action Class, and Keyboard class. In this blog article, you will learn the nuances between these methods.

WebElement SendKeys

Everyone is well aware of the fact that SendKeys method is mostly used to enter value in a textbox or file path in File inputbox. Take for instance if you wish to paste the value which is available in clipboard using CTRL + V in a textbox.

txtBox = driver.find_element_by_id("txt1")

#Pastes the clipboard value in the textbox
txtBox.send_keys(Keys.LEFT_CONTROL, 'v')
  

The above snippet pastes the value in the textbox. Now, you want to enter a string after pasting the clipboard.

txtBox.send_keys(Keys.LEFT_CONTROL, 'v', 'Codoid')
  

When you execute the above code, it won’t accept the string (i.e. Codoid). Because the modifiers keys (i.e. CTRL/ALT/SHIFT/etc) will not be released until SendKeys call is complete.

To understand the above precisely, pass the third argument text as ‘value’ and rerun the snippet.

txtBox.send_keys(Keys.LEFT_CONTROL, 'v', 'value')

If you notice the execution, the snippet has pasted the clipboard text twice. The reason is CTRL key is released only after the SendKeys method call.

CTRL key is not released yet and the third argument (‘value’) string’s starting letter is ‘v’. So again CTRL + V is pressed. That’s why the clipboard text is pasted twice in the textbox.

Then how to enter the argument text in the textbox? Just use KEYS.NULL after CTRL + V. Refer the below snippet.

txtBox.send_keys(Keys.LEFT_CONTROL, 'v', Keys.NULL, 'value')
  

As soon as Keys.NULL is used all the modifier keys will be released.

Action Class Sendkeys

Using Action class’ SendKeys methods, you can’t press modifier keys. Try the below code, it won’t paste the clipboard content as we tried using WebElement’s Sendkeys method.

action = ActionChains(driver)

action.send_keys_to_element(txtBox, Keys.LEFT_CONTROL, "v").perform()
  

You need to use KeyDown to press modifiers keys. Try with the below code, it will paste the text in the textbox.

action.key_down(Keys.LEFT_CONTROL).send_keys_to_element(txtBox, "v").perform()
  

In conclusion

We as an automation testing company, have mitigated several unsuccessful automation testing projects. Gaining enduring technical know-how of selenium basics to advanced level is a key to test automation success.

Comments(0)

Submit a Comment

Your email address will not be published. Required fields are marked *

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility