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

用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)
 end
 

describe "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)函数

 

 

转载于:https://www.cnblogs.com/timsheng/archive/2012/09/14/2685277.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值