2011-08-12 27 views
1

我正在用Ruby構建一個簡單的新聞聚合器。我對這門語言是完全陌生的,我只是發現瞭如何使用open uri函數。編寫一個簡單的Ruby腳本(帶開放URI)

現在,我的問題是如何解析html頁面。 Ruby中是否有內置的解析器?

順便說一句,我不使用的軌道,我想這是非常簡單的

提前感謝!

回答

1

簡單的答案是肯定的,有一個解析器。我不能明確回答你的問題,不知道你想從HTML中提取什麼,但我已經包含了下面的一些源代碼。如果你能夠閱讀紅寶石代碼,那麼它是非常明顯的。

require 'open-uri' 
require 'pp' 
open('http://ruby-lang.org') do |f| 
puts "URI: #{f.base_uri}" 
puts "Content-type: #{f.content_type}, charset: #{f.charset}" 
puts "Encoding: #{f.content_encoding}" 
puts "Last modified: #{f.last_modified}" 
puts "Status: #{f.status.inspect}" 
pp f.meta 
puts "----" 
3.times {|i| puts "#{i}: #{f.gets}" } 
end 

生產:

URI: http://www.ruby-lang.org/en/ 
Content-type: text/html, charset: utf-8 
Encoding: [] 
Last modified: 
Status: ["200", "OK"] 
{"date"=>"Mon, 15 Nov 2010 17:54:07 GMT", 
"server"=> 
"Apache/2.2.3 (Debian) DAV/2 SVN/1.4.2 mod_ruby/1.2.6 Ruby/1.8.5(2006-08-25)", 
"transfer-encoding"=>"chunked", 
"content-type"=>"text/html;charset=utf-8"} 
---- 
0: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
1: "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
2: <html xmlns="http://www.w3.org/1999/xhtml"> 

這裏的展示開放的URI如何使用例子的又一個鏈接:http://juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/