2012年8月17日 星期五

Nokogiri

想不到 太久沒寫 Ruby

當時好用的 HTML Parser 工具 hpricot 已經終止了

不過還好還有 Nokogiri

以前使用過 hpricot 的朋友

可以完全無痛移植 Nokogiri

 C:\DevKit>gem install nokogiri
Fetching: nokogiri-1.5.5-x86-mingw32.gem (100%)
Successfully installed nokogiri-1.5.5-x86-mingw32
1 gem installed
Installing ri documentation for nokogiri-1.5.5-x86-mingw32...
Installing RDoc documentation for nokogiri-1.5.5-x86-mingw32...

一樣快速好用歐 並且支援 xpath, css, tag屬性 搜尋




require 'nokogiri'
require 'open-uri'

# Get a Nokogiri::HTML:Document for the page we’re interested in...

doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))

# Do funky things with it using Nokogiri::XML::Node methods...

####
# Search for nodes by css
doc.css('h3.r a').each do |link|
puts link.content
end

####
# Search for nodes by xpath
doc.xpath('//h3/a').each do |link|
puts link.content
end

####
# Or mix and match.
doc.search('h3.r a.l', '//h3/a').each do |link|
puts link.content
end




沒有留言:

張貼留言