Ruby

Programming Ruby (22) 기본 입출력 - 2

weicome 2016. 11. 7. 23:52
[출처] Programming Ruby 
(본 게시물은 저작권의 문제 발생시 출판사의 요청에 의해 삭제될 수 있습니다.)


네트워크로 통신하기


Socket 클래스를 이용해 HTTP OPTIONS 요청을 사용해서 로컬 엡 서버에 있는 사용자 웹 사이트에 대한 정보를 가져오는 예제이다.


require 'socket'


client = TCPSocket.open('127.0.0.1', 'www')

client.send("OPTIONS /~dave/ HTTP/1.0\n\n", 0)      # 0은 표준 패킷을 의미한다.

puts client.readlines

client.close


실행결과

HTTP/1.1 200 OK

Date: Thu 14 nov ~~

Server: Apache/2.2.24 

Allow: GET,HEAD,POST,OPTIONS     

Content-Length: 0

Connection: close

Content-Type: httpd/unix-directory 



고수준 네트워킹과 관련해서 lib/net의 라이브러리들이 FTP, HTTP 등을 다로는 모듈을 제공한다. 


다음 예제는 Progragmatic Programmers 홈페이지에서 사용하는 이미지 목록을 표시하는 예제이다.


require 'net/http'


http = Net::HTTP.new('progprog.com', 80)

response = http.get('/book/ruby3/programming-ruby-1-9')


if response.message == "OK"

     puts response.body.scan(/<img alt=".*?" src="(.*?)"/m).uniq[0,3]

end


실행결과

bla

bla~



open-uri 라이브러리를 프로그램에 require 하면 Object#open 메서드가 http://와 ftp://  같은 URL을 파일 이름처럼 인식한다. 


require 'open-uri'


open('http://pragprog.com') do | f |

     puts f.read.scan(/<img alt=".*?" src="(.*?)"/m).uniq[0,3]

end


실행결과

http://

http://

http://imagery.



HTML 파싱


HTML로 웹 사이트를 읽어와서 여러 정보를 분석할 수 있다. 다음 예제는 정규 표현식 리터럴을 사용한다. 


require 'open-uri'

page = open('http://pragprog.com/titles').read

if page =~ %r{<title>(.*?)</title>}m

     puts "Title is #{$1.inspect}"

end


실행결과

This is "The Progmatic Bookshelf | Programming Ruby 1.9"



정규 표현식 유명한 라이브러리인 노코기리라는 라이브러리다. 


require 'open-uri'

require 'nokogiri'


doc nokogiri::HTML(open("htp://pragprog.com/"))


puts "Page title is " + doc.xpath("//title").inner_html


# id="copyright" 속성을 가진 div의 첫 번째 문단을 출력한다. 

# nokogiri 는 xpath 와 css 형식의 셀렉터(selector)를 모두 지원한다.


puts doc.css('div#copytight p')


# site-links div 요소 안의 두 번째 링크를 각각 xpath와 css 실렉터를 사용해 출력한다.

puts "\nSecond hyperline is"

puts doc.xpath('id("site-links")//a[2]')

puts.doc.css('#site-link a:nth-of-type(2)')


실행결과

Page title is The Pragmatic Bookshelf

<p>

     the <em> Progmatic Bookshelfs bla

     #

     #..

</p>


Second hyperlink is

<a href="http://progprog.com/aobut">About us</a>


노코기리를 사용하면 HTML과 XML을 갱신하거나 생성할 수도 있다. 


















끄읕.