Windows7でruby2、open-uriを使ってWebページを取得

Windows7にruby2をインストールし、open-uriを使ってWebページを取得するサンプルを作成しました。
 

(1)Windows7にruby2.0をインストール


 
1)Ruby2.0.0-p598インストール
http://rubyinstaller.org/downloads/
 
rubyinstaller-2.0.0-p598.exeを取得し、ダブルクリックでインストール
 
2)Ruby Development Kitをインストール
 
下記サイトの手順に従ってインストール
https://github.com/oneclick/rubyinstaller/wiki/development-kit
 
①ファイルダウンロード(Ruby 2.0 and 2.1 (32bits version only))
DevKit-mingw64-32-4.7.2-20130224-1151-sfx.exe
 
②上記ファイルを解凍
ここでは、”C:\rubydevkit2″に解凍
 
③config.yml作成
 
スタート→”Rubyコマンドプロンプトを開く”
C:\>cd rubydevkit2
C:\rubydevkit2>ruby dk.rb init
[INFO] found RubyInstaller v1.9.3 at C:/Ruby193
[INFO] found RubyInstaller v2.0.0 at C:/Ruby200
 
Initialization complete! Please review and modify the auto-generated
‘config.yml’ file to ensure it contains the root directories to all
of the installed Rubies you want enhanced by the DevKit.
 
④Rubyのリストを確認
 
C:\rubydevkit>ruby dk.rb review
Based upon the settings in the ‘config.yml’ file generated
from running ‘ruby dk.rb init’ and any of your customizations,
DevKit functionality will be injected into the following Rubies
when you run ‘ruby dk.rb install’.
 
C:/Ruby193
C:/Ruby200
 
⑤インストール
 
C:\rubydevkit2>ruby dk.rb install
[INFO] Skipping existing gem override for ‘C:/Ruby193’
[WARN] Skipping existing DevKit helper library for ‘C:/Ruby193’
[INFO] Updating convenience notice gem override for ‘C:/Ruby200’
[INFO] Installing ‘C:/Ruby200/lib/ruby/site_ruby/devkit.rb’
 
⑥動作確認
 
C:\rubydevkit2>gem install poppler
ERROR: Could not find a valid gem ‘poppler’ (>= 0), here is why:
Unable to download data from https://rubygems.org/ – SSL_connect retur
ned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (
https://rubygems.org/latest_specs.4.8.gz)
 
エラーの原因はよく分かりませんが、下記のようにオプションを指定したら実行できました。
 
C:\rubydevkit2>gem install poppler –source http://rubygems.org
 

(2)ruby2、open-uriを使ってWebページを取得


 
下記サンプルのようにopen-uriを使って普通のファイルのように取り扱う事が出来ます。
 
1)取得したWebページを出力

require 'open-uri'
open("http://localhost/ng/offcanvas.html") {|f|
  puts f.read
}

 
2)取得したWebページを1行ずつ出力

require 'open-uri'
open("http://localhost/ng/offcanvas.html") {|f|
  f.each_line {|line| p line}
}
関連記事の目次

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください