用ruby抓取gzip网页

require 'net/http'
require 'uri'
module Net
  class HTTP
    def HTTP.get_with_headers(uri,headers=nil)
      uri=URI.parse(uri) if uri.respond_to? :to_str
      start(uri.host,uri.port) do |http|
        return http.get(uri.path,headers)
      end
    end
  end
end

gzipped = Net::HTTP.get_with_headers('http://www.qidian.com/','Accept-Encoding' => 'gzip')
puts gzipped.body.size
require 'zlib'
require 'stringio'
body_io=StringIO.new(gzipped.body)
unzipped_body=Zlib::GzipReader.new(body_io).read
puts unzipped_body

你可能感兴趣的:(.net,Ruby)