| Memoize | BasicWerk
						 
						EC Support
						 
						Technique
						 
						Facebook | 
| 20140817220350_ruby_open_uri_kconv | 
| ruby_open_uri_kconv 
 Web ページの情報を取得する。 open-uri を使う。 
 と、その前に get したページの内容をターミナルに(正常に)表示させるにはエンコードを合わせる必要がある。 
 僕の環境だと、 % echo $LANG ja_JP.UTF-8 となっているから、Web ページの charset が UTF-8 以外だと文字化けする可能性がある。 
 そこでエンコード変換モジュールの kconv を併用する。http_content.rb 
 
#! /usr/bin/ruby
# coding: utf-8
 
require 'open-uri'
require 'kconv'
uri = ARGV.first
 
open(uri) do |f|
    content = f.read
    unless f.charset == "utf-8"
        content = content.toutf8
    end
    puts content
end
 
 f.read の部分が実際にコンテンツの内容を読み込んでるところ。 その後、コンテンツの charset を確認し、UTF-8 でなければ(元が何であろうと)kconv#toutf8 で UTF-8 に変換し、ターミナルで文字化けしないようにしている。 
 例えば、楽天の charset は EUC-JP だが、このスクリプトは問題なく動作する。 % http_content.rb "http://www.rakuten.co.jp/" <!DOCTYPE html> <html lang="ja" xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" ... > <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-JP"> ... ... <title> 【楽天市場】Shopping is Entertainment! : インターネット最大級の通信販売、... ... # ・・・以下省略・・・ 
 | 
| © Shin Nakamura/BasicWerk 2014 |