您的位置:首页 > 编程语言 > Ruby

ruby webdriver如何解决中文乱码问题

2012-09-14 17:16 260 查看
用ruby编写webdriver脚本,有时经常会遇到中文乱码的问题,统一字符集可以解决这些问题

1.首先确认ide的保存方式是否和访问的页面一致,如果不一致的话请设置为一致

2.有时会同时访问多个页面,或者多个iframe,或者既访问页面和iframe的情况,这个时候,需要确认每个页面和iframe的字符编码的格式分别为什么,然后作相应的转码

require 'iconv'

def gbk2utf8(string)
Iconv.conv('utf-8','gbk',string)
end

def utf82gbk(string)
Iconv.conv('gbk','utf-8',string)
end


gbk2utf8(string)是将gbk格式转换为utf8

utf82gbk(string)是将utf8格式转换为gbk

奉上实例

#encoding : gbk

require 'selenium-webdriver'

require 'iconv' def gbk2utf8(string) Iconv.conv('utf-8','gbk',string) end def utf82gbk(string) Iconv.conv('gbk','utf-8',string) enddescribe "soso mainpage login" do

it "should return username and password is wrong" do

chrome = Selenium::WebDriver.for :chrome

url = 'http://www.soso.com'

chrome.get url

link = chrome.find_element(:link_text,'登录')

link.click

sleep 2

chrome.switch_to.frame('login_frame')

chrome.find_element(:id,'u').send_keys("278570038")

chrome.find_element(:id,'p').send_keys("4444")

chrome.find_element(:id,'login_button').click

aa = chrome.find_element(:id,'err_m').text

bb = utf82gbk(aa)

#~ puts chrome.find_element(:id,'err_m').text

bb.should eql("您输入的帐号或密码不正确,请重新输入。意见反馈")

end #it

end #describe


搜搜首页:http://www.soso.com的字符编码是gbk

点击登录后打开的iframe是utf-8格式

脚本设置的字符编码格式是gbk
所以当获取的text文本(utf-8格式)与脚本中eql(string)函数中的中文进行比较时,需要将text文本转换成gbk格式的,即调用utf82gbk(string)函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: