如何使watir-webdriver支持选择中文的下拉菜单
今天将waitr代码移植至watir-webdriver时,发现watir-webdriver的Select.select(text)方法似乎不支持中文的text。
也就是说watir-webdriver的select方法无法选择中文的option。
研究了一下源码发现Select.select方法是这样实现的:
def select(str_or_rx) select_by :text, str_or_rxend#select方法又调用了select_by方法def select_by(how, str_or_rx) assert_exists case str_or_rx when String, Numeric select_by_string(how, str_or_rx.to_s) when Regexp select_by_regexp(how, str_or_rx) else raise TypeError, "expected String or Regexp, got #{str_or_rx.inspect}:#{str_or_rx.class}" endend#当select的参数是String的时候调用select_by_string方法def select_by_string(how, string) xpath = option_xpath_for(how, string) if multiple? elements = @element.find_elements(:xpath, xpath) no_value_found(string) if elements.empty? elements.each { |e| e.click unless e.selected? } elements.first.text else begin e = @element.find_element(:xpath, xpath) rescue WebDriver::Error::NoSuchElementError no_value_found(string) end e.click unless e.selected? safe_text(e) endend#select_by_string方法调用了option_xpath_for方法来生成该option的xpathdef option_xpath_for(how, string) string = XpathSupport.escape string case how when :text ".//option[normalize-space()=#{string} or @label=#{string}]" when :value ".//option[@value=#{string}]" else raise Error, "unknown how: #{how.inspect}" endend
Watir::Option.class_eval do def value assert_exists @element.attribute(:value) endendWatir::Select.class_eval do def getAllContents contents = [] options.each do |o| contents.push o.text rescue next end #each contents end #def alias :get_all_contents :getAllContents def getAllValues values = [] options.each do |o| values.push o.value end values end #def alias :get_all_values :getAllValues # 返回select list 下所有的option # 提供value => text的键值对 def text_to_value the_hash = {} values = getAllValues getAllContents.each_with_index do |t, i| the_hash[t] = values[i] end the_hash end #def def my_select text #也可以直接覆盖原生select方法 begin select text rescue select_value text_to_value[text] end endend #class eval