---
title: "说说watir-webdriver那些事（十四）模拟键盘操作"
author: "dtrex"
date: "2012-03-15T14:11:13Z"
tags: []
categories: ["编程语言"]
slug: "watir-webdriver"
draft: false
lastmod: "2012-03-15T14:29:00Z"
id: 1454183
url: "https://dtrex.iteye.com/blog/1454183"
---

一个web功能自动化测试工具应该具备三个基础属性：

1.可以定位web的DOM元素，这个我在前面的定位已经讲过了

2.可以执行js脚本，这个不仅是上一章说的执行js，还包括对控件的写js操作

3.模拟键盘鼠标进行操作。

 

前两点，已经在前面都谈过了，下面讲讲第三点，模拟操作，首先说说模拟键盘操作：

 

## 键盘模拟

如果用过Selenium的话，会知道神奇的send\_keys几乎涵盖了所有的输入操作，那么Watir-webdriver也是一样的模拟键盘的操作，可以使用这条命令，比方说，我想在页面上大一个回车

 

```
b.send_keys :enter
```

 

 当然你会遇到组合键和连续按键，可以这样做

 

```
b.element.send_keys [:control, 'a'], :backspace
```

 额，神奇的事情还有

 

```
b.text_field.send_keys("hello")
```

 当然别忘了，鼠标单击的时候，你想加入其他按键

 

```
b.element.click(:shift, :control)
```

 好吧，几乎是无所不能的键盘模拟啊，下面了列出一些特殊按键的名称以供参考：

- :null
- :cancel
- :help
- :backspace
- :tab
- :clear
- :return
- :enter
- :shift
- :left\_shift
- :control
- :left\_control
- :alt
- :left\_alt
- :pause
- :escape
- :space
- :page\_up
- :page\_down
- :end
- :home
- :left
- :arrow\_left
- :up
- :arrow\_up
- :right
- :arrow\_right
- :down
- :arrow\_down
- :insert
- :delete
- :semicolon
- :equals
- :numpad0
- :numpad1
- :numpad2
- :numpad3
- :numpad4
- :numpad5
- :numpad6
- :numpad7
- :numpad8
- :numpad9
- :multiply
- :add
- :separator
- :subtract
- :decimal
- :divide
- :f1
- :f2
- :f3
- :f4
- :f5
- :f6
- :f7
- :f8
- :f9
- :f10
- :f11
- :f12
- :meta
- :command

## 鼠标模拟

在使用过程中，经常遇到模拟鼠标的操作，这个部分其实在watir-webdriver中比较难以完美的实现。有很多方法去比较，比方说如果要模拟鼠标mouseover的情况，可以使用fire\_event函数触发该事件，或者使用js方法来调用改事件，还有一个方法就是使用底层的seleneium-webdriver的action方法：

```
require 'rubygems'
require 'selenium-webdriver'
dr = Selenium::WebDriver.for :firefox
select_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'fire_event.html'))
dr.navigate.to select_file
 
m = dr.find_element(:css => '.mo')
10.times do
    dr.action.move_to(m).perform
end
```

 这个一段别人写的方法，这种底层的selenium的Action方法是使用java的ACTION类来模拟鼠标操作，来模拟mouseover事件。

当然你也可以使用ruby调用Win32api来模拟鼠标的移动，不过这种情况下要计算好坐标，我把相关代码贴出来，具体使用的时候，可能还需要计算坐标的位置，和将网页置顶（这种方式不符合自动化测试工具的基本的设计理念，就是多个浏览器并行执行，如果模拟鼠标位置，那么就只能将一个网页置顶，才有效果）

```
#要求ruby1.8.x
require 'Win32API'

#定义API GetCursorPos和SetCursorPos的接口
get_cursor_pos = Win32API.new("user32","GetCursorPos",['p'],'v')
$set_cursor_pos = Win32API.new("user32","SetCursorPos",['i']*2,'v')

#获取鼠标位置
lpPoint =" " * 8    #初始化存储位置信息的变量
get_cursor_pos.Call(lpPoint)        #调用API
x, y = lpPoint.unpack("LL")        #将传回的参数转换为两个无符号的长整数
puts "当前鼠标的坐标为： #{x}, #{y}"

#设置鼠标位置
def setm(new_xy)
  p new_xy
  $set_cursor_pos.Call(new_xy[0], new_xy[1])
end

100.times{
  setm([rand*800,rand*600])
  sleep 0.01
}
```

 

老实说，我觉得效果都不是很好，在具体情况下，还是尽量寻找规避的方法。推荐使用fire\_event来触发事件