The differences between type, keyPress and keyPressNative in Selenium

A friend asked me how to press the ENTER key in Selenium RC. A simple enough request? Just send the right JS key code? Well not quite - Selenium has issues with text input. For many forms where you need to just enter a few words, a date of birth or ZIP/Postal code, Selenium performs just fine. But if you need to enter text into a TextArea, and do things like: use the ENTER key - and type text character by character - Selenium gets a bit more flaky.

The issue stems from a bug in IE, where sending Javascript key press events does not necessarily mean IE will accept/display them. This affects the Selenium type_keys method. You can work around this by using type method. But this has its own drawbacks, such as not firing the appropriate keyboard events, or overwriting the existing contents of a field rather than appending.

There is a solution. Selenium 1.0 has another method of entering text, key_press_native. Key_press_native uses Java's UI Robot (java.awt.robot) to enter text into text input boxes and textareas. The 3 methods key_press_native, key_down_native and key_up_native are all you need to enter most characters. The downside is that the methods currently only accept Java Key Codes only, rather than regular strings.

So if you want to input into textarea two lines, such as "a\na", you should write code in java below:

selenium.type("name=notes", "a"); //input "a" into textarea with name "notes"
selenium.setCursorPosition("name=notes", "-1"); // you must set cursor before keyPressNative
selenium.keyPressNative(String.valueOf(KeyEvent.VK_ENTER)); // press enter
selenium.keyPressNative("65"); //press another "a"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值