最好的Rails HTML解析器

ewa*_*ned 5 html ruby parsing

我知道Hpricot仍然是一个标准,但我记得听说过一个更快,更富有表现力的Ruby解析器.

有人知道它叫什么,是否值得从Hpricot转换?

提前致谢

Wes*_*ing 11

你可能在考虑Nokogiri.我自己没有使用它,但"每个人"都在谈论它,基准测试看起来很有趣:

hpricot:html:doc  48.930000 3.640000 52.570000 ( 52.900035)
hpricot2:html:doc  4.500000 0.020000  4.520000 (  4.518984)
nokogiri:html:doc  3.640000 0.130000  3.770000 (  3.770642)
Run Code Online (Sandbox Code Playgroud)


ibl*_*lue 5

有多种工具可供选择.我用Nokogiri.

演示:

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::HTML(%{
  <h1 class="title">Hello, World</h1>
  <p>Some text</p>
  <a href="http://www.google.com/">Some link</a>
})

title   = doc.at_css("h1.title").text
content = doc.at_css("p").text
url     = doc.at_css("a")[:href]
Run Code Online (Sandbox Code Playgroud)

Ryan Bates做了一个关于使用它的精彩截屏:#190:用Nokogiri进行屏幕刮擦.

文档:http://nokogiri.org/

教程:http://nokogiri.org/tutorials