爬虫遇见的编码问题汇总

问题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("&nbsp;","")
    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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值