【记录】Watir中的中文问题

转自:http://www.blogjava.net/raimundox/archive/2006/01/12/27676.html

Watir doesn't work well with chinese characters. Try the following codes.

ie.text_field(:name, 'some text field).set('某某')
It will highlight the text field but put nothing in it. I read the Watir source codes, and found an interesting code segment:

1 for i in 0 .. value.length-1
2 sleep @ieController.typingspeed # typing speed
3 c = value[i,1]
4 #@ieController.log " adding c.chr " + c #.chr.to_s
5 @o.value = @o.value.to_s + c #c.chr
6 fire_key_events
7 end
The above codes show how Watir simulates typing.If it doesn't work well with chinese characters, There must be something wrong with Ruby string. The first order of business is to figure out how Ruby string works for Chinese string.

1 chineseString = '某某'
2 puts chineseString.length
3 for i in 0..chineseString.length-1
4 puts chineseString[i, 1]
5 end
result will be:

4

Does Ruby, which is now capturing all java programmers' love, use 8bit char instead of unicode? Holy fuck!

I made a simple patch for the issue after I woke up from a short coma.

1 require 'Watir'
2
3 module Watir
4 module Cn
5 class IE maxLength
16 value = suppliedValue[0 .. maxLength ]
17 @ieController.log " Supplied string is #{suppliedValue.length} chars, which exceeds the max length (#{maxLength}) of the field. Using value: #{value}"
18 end
19 rescue
20 # probably a text area - so it doesnt have a max Length
21 maxLength = -1
22 end
23
24 Cn.characters_in(value) {|c|
25 sleep @ieController.typingspeed
26 @o.value = @o.value.to_s + c
27 fire_key_events}
28 end
29 end
30
31 def Cn.characters_in(value)
32 index = 0
33 while index < value.length
34 len = value[index] > 128 ? 2 : 1
35 yield value[index, len]
36 index += len
37 end
38 end
39 end
40 end
I submitted this patch to Watir tracing systsem,and zipped codes could be found here:
http://rubyforge.org/tracker/index.php?func=detail&aid=3232&group_id=104&atid=489

下面的评论也比较有帮助:
This might help -> http://ruphus.com/blog/2005/06/11/ruby-and-unicode/
-----
# 呵呵,过时了,1.5发布了,下面是针对1.5的修改办法
把下面的屏蔽或删除
#for i in 0 .. value.length-1
# sleep @container.typingspeed
# c = value[i,1]
# #@container.log " adding c.chr " + c #.chr.to_s
# @o.value = @o.value.to_s + c #c.chr
# @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")
}
我喜欢让他sleep 0,这样更快一些

characters_in方法还是桃之夭夭原来的方法:

def characters_in(value)
index = 0
while index < value.length
len = value[index] > 128 ? 2 : 1
yield value[index, len]
index += len
end

好运~
end

评论

-.-#

-.-# RSS为啥不全文输出。。