问题1
中文:北京 在浏览器(chrome)中被转换成 %B1%B1%BE%A9
同时打开浏览器中发现 (unable to decode value)
解决方法:
通过: URI.decode("%B1%B1%BE%A9")
结果是\xB1\xB1\xBE\xA9
(gb2132的编码格)
require 'uri'
#对中文先进行一次编码
str = "北京".encode("gb2312")
#再用URI对str进行一次encode
res = URI.encode(str)
下面是阿里旅行的一个链接
http://hotel.alitrip.com/hotel_list3.htm?cityName="#{res}"&city=&keywords=&checkIn=2016-03-20&checkOut=2016-03-21
有些网站转码之后 北京被转换成:%E5%8C%97%E4%BA%AC
这种形式
通过: URI.decode("%B1%B1%BE%A9")
结果就是[北京],所以在链接中直接对中文进行一次encode即可
require 'uri'
#进行一次encode即可
res = URI.encode("北京")
2.获取下来的doc的编码格式的转换
第一种:网站是GBK编码的时候获取下来的html源码一片乱码
可以使用Iconv
对html进行一次转码 转成utf-8格式
require 'mechanize'
require 'hpricot'
require 'httpclient'
require 'iconv'
class String
def to_utf8
Iconv.conv("UTF-8","GBK",self)
end
//def to_utf8
// Iconv.conv("UTF-8//IGNORE","GBK//IGNORE",self)
// end
end
@client = Mechanize.new
link = "http://www.lread.net/read/70/48150.html"
doc = @client.get(link).body.to_utf8
puts doc
常用转换:
require "iconv"
class String
def gsub_html
# return "" if self == nil || self == ""
self.gsub(/\r|\t|\n/,"").gsub(/<(\S*?)[^>]*>.*?|<.*? \/>/,"").gsub(" ","")
end
def to_gb
Iconv.conv("gb2312//IGNORE","UTF-8//IGNORE",self)
end
def utf8_to_gb
Iconv.conv("gb2312//IGNORE","UTF-8//IGNORE",self)
end
def gb_to_utf8
Iconv.conv("UTF-8//IGNORE","GB18030//IGNORE",self)
end
def to_utf8
Iconv.conv("UTF-8//IGNORE","GBK//IGNORE",self)
end
def shiftJIS_to_utf8
self.force_encoding("UTF-8")
end
end