• 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)函数

  • 相关阅读:
    angularjs中的jqlite的认识理解及操作使用
    轻谈Normalize.css
    oppo R9 WLAN使用代理图解
    前端小炒的win7使用笔记(收藏篇)
    git操作方便,简单使用的客户端sourcetree 安装配置所遇问题总结
    关于js中对事件绑定与普通事件的理解
    IT最新最火的网络词汇*2*(文章来源电商)
    Git笔记之初识vi编辑器
    番茄钟工作法--我们天生爱分享
    探讨"点"语法的奥秘
  • 原文地址:https://www.cnblogs.com/timsheng/p/2685277.html
Copyright © 2020-2023  润新知