socket、net/http、open-uriライブラリを使用して、Webページをフェッチするコード。
Body部だけを表示します。
(socket)
#!/usr/bin/ruby require 'socket' host = 'www.hogehoge.com' port = 80 index_path = '/index.html' # WebページをfetchするためのHTTPリクエスト req = "GET #{index_path} HTTP/1.0\r\n\r\n" # Webサーバへ接続 socket = TCPSocket.open(host,port) # Webサーバへリクエストを送る socket.print(req) # Webサーバからのレスポンスを受け取る res = socket.read # ヘッダとボディ部に分割 headers,body = res.split("\r\n\r\n",2) # ボディ部を1行づつ出力 body.each do |res_line| puts res_line end
(net/http)
#!/usr/bin/ruby require 'net/http' host = 'www.hogehoge.com' index_path = '/index.html' # Webサーバへ接続 http = Net::HTTP.new(host) # Webサーバからレスポンス(ヘッダとボディ)を受け取る header,body = http.get(index_path) # ボディ部を1行づつ出力 body.each do |res_line| puts res_line end
(open-uri)
#!/usr/bin/ruby require 'open-uri' target='http://www.hogehoge.com/index.html' open(target) {|con| con.each do |line| puts line end }