Watir对中文缺乏原生的支持,就算是最新的版本,使用中文也会出现乱码、方块的现象。
Google了许久,最佳的解决方案是来自于:http://jonny131./blog/654160
修改 c:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir\win32ole.rb 文件中的下面代码WIN32OLE.codepage = WIN32OLE::CP_UTF8
修改为
WIN32OLE.codepage = WIN32OLE::CP_ACP
PS:只能修改该文件,在调用Watir的代码中设置OLE的codepage测试无效。
另外一种方式来自于:http://www.cnblogs.com/slaughter/archive/2007/10/18/929385.html,http://www./raimundox/archive/2006/01/11/27549.html
1.打开watir.rb
2.在class TextField中加入一个新的method:
def characters_in(value)
index = 0
while index < value.length
len = value[index] > 128 ? 2 : 1
yield value[index, len]
index += len
end
end
3.更改class TextField的doKeyPress( value )方法部分代码,将下面代码
——————————————-
for i in 0 .. value.length-1
sleep @container.typingspeed
c = value[i,1]
@container.log ” adding c.chr ” + c
@o.value = @o.value.to_s + c
@o.fireEvent(“onKeyDown”)
@o.fireEvent(“onKeyPress”)
@o.fireEvent(“onKeyUp”)
end
替换为如下代码
characters_in(value) {|c|
sleep @container.typingspeed
@o.value = @o.value.to_s + c
@o.fireEvent(“onKeyDown”)
@o.fireEvent(“onKeyPress”)
@o.fireEvent(“onKeyUp”)
}
在http:///tracker/index.php?func=detail&aid=3232&group_id=104&atid=489,可以下载到watir_cn的补丁。
这两种方式测试都是有效的。
发现无论浏览器中页面的编码是GBK或者UTF-8,通过OLE传入IE的都必须为GBK的字符才行。试图设置WinOLE的codepage为utf8,并传入utf8的中文字符完全不可行!因此在使用Watir的时候,得把所有UTF8的中文转换成GBK先。