zoukankan      html  css  js  c++  java
  • 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)函数

  • 相关阅读:
    openwrt的内核版本是在哪个文件中指定的?
    git如何将一个分支合并到另一个分支?
    cygwin如何下编译安装tmux?
    如何合并ts文件?
    在cygwin下创建的文件位于windows的哪个目录下?
    linux shell的for循环语法是怎样的?
    内部类访问局部变量时,为什么需要加final关键字
    Java8函数式编程的宏观总结
    Maven私服使用经验总结
    java关于Integer设置-128到127的静态缓存
  • 原文地址:https://www.cnblogs.com/timsheng/p/2685277.html
Copyright © 2011-2022 走看看