Hpricot XML,HTML解析工具。
Hpricot 安装:
gem installhpricot ; 或许需要devkit。
使用:require ‘hpricot’ 之前需要require ‘rubygems’
另外需要: require‘open-uri’
例子:
doc = Hpricot(open(name))
name 为URL或者文件。
检索:doc.search(tag) 检索HTML中的tag标签。
如HTML中有 <h2 align="center">cashpro Summary Report</h2>
则 doc.search(“h2”)
会检索出 <h2 align="center">cashpro Summary Report</h2>
如果doc.search(“h2”).inner_html 则结果: cashpro Summary Report
如果需要检索标签中的某个属性(对于抓取HTML中的链接十分有用):
例如:<a href="/quality_reports/codedetail.html" style="color:#000000">Details</a>
现在需要 href这个属性的值, 即URL: /quality_reports/codedetail.html
语法如下:doc.search("a").map {|e| e.get_attribute('href') }
很多时候得到这种相对路径是没用的, 我们需要把它改成绝对路径,则可以这么做:
doc.search("a").map {|e| “http://www.baidu.com” + e.get_attribute('href') }
于是就得到结果:http://www.baidu.com/quality_reports/codedetail.html
参考:http://hpricot.com/demonstrations