'Ruby'에 해당되는 글 1건

  1. [Ruby] 웹 소스 긁어오기 2009.01.01

[Ruby] 웹 소스 긁어오기[Ruby] 웹 소스 긁어오기

Posted at 2009. 1. 1. 16:35 | Posted in 프로그래밍 언어/Ruby
웹 소스..라기 보단 웹 요청에 대한 결과물 html 소스라고 해야할까.
PHP에서 하던 것처럼 소켓으로 웹 페이지를 요청하여 그 결과를 받아오는 식으로 코딩하였다.

class TinyWebBrowser
    require 'socket'
   
def initialize(host, port)
       
@host = host
        @port = port
        @socket = TCPSocket.new(host, port)
    end
    def print_page(path)
        request = "GET #{path} HTTP/1.0\r\n"
        request += "Host: #{@host}\r\n"
        request += "Connection: Close\r\n\r\n"
        @socket.write(request)
        response = @socket.read
        return response.split("\r\n\r\n", 2) # 헤더와 웹 소스 분리
   
end
    def close_browser
        @socket.close
    end
end

if __FILE__ == $0
    wb = TinyWebBrowser.new('berorev.pe.kr', 80)
    header, body = wb.print_page('/index.php')
   
File.open('out.txt', 'w') do |fp|
        fp.puts body
   
end
    wb.close_browser
end

HTTP/1.1로 전송해 봤더니 결과의시작과 끝에 17856과 0 이라는 숫자가 붙어 있었다.
1.0으로 보내 봤더니 깔끔하네;; 이유는 잘 모르겠다..'ㅡ';;

여튼 print_page를 호출한 결과로 html 소스를 얻어 보통 정규식 등의 작업을 진행할 것이다.


그런데.... 이미 라이브러리로 만들어진 게 있네.. 이런!!
require 'net/http'
html = Net::HTTP.get 'berorev.pe.kr', '/index.php'
File.open('out2.txt', 'w') do |fp|
     fp.puts html
end

//