hpricot,rails的解析html插件

pricot 是快又好用的 Ruby HTML parser,来源 JQuery。它的特点是 1.速度快,因为核心用C改写了 2.好用的介面,你可以用CSS selectors,element IDs,tag types 等。

其它特点可以解析 XML,可以解析 invaild 的 HTML,甚至可以更改 document 结构。

open-uri中文说明


hpricot官方git地址

Ruby代码
  1. require 'open-uri'  
  2. doc = open("http://qwantz.com/") { |f| Hpricot(f) }  
Ruby代码
  1. require 'rubygems'  
  2. require 'hpricot'  
  3. document = <<END  
  4. <ul>  
  5. <li>first item</li>  
  6. <li>second item</li>  
  7. </ul>  
  8. END  
  9. doc = Hpricot.parse(document)  
  10. (doc/'li').each do |item|  
  11. puts item.inner_html#输出内容  
  12. end  
Ruby代码
  1. require 'rubygems'  
  2. require 'hpricot'  
  3. require 'open-uri'  
  4. url = "http://www.abc.com/news/news_msg.php”  
  5. doc = Hpricot(open(url))  
  6. doc.search(’table tr td div.tbCopy font’).each do |item|  
  7. (item/’a').each do |nav|  
  8. puts nav.attributes['href']#读取属性  
  9. puts nav.inner_html  
  10. end  
  11. end  
posted @ 2009-08-24 18:22  麦飞  阅读(529)  评论(0编辑  收藏  举报