http://chaos-fractal.blogspot.com/2011/11/ruby.html
●例1
require 'rubygems'
require 'nokogiri'
doc = Nokogiri::HTML.parse(<<-eohtml)
<title>Hello World</title>
<h1>
This is an awesome document</h1>
I am a paragraph
<a href="http://google.ca/">I am a link</a>
eohtml
####
# Search for nodes by css
doc.css('p > a').each do |a_tag|
puts a_tag.content
end
####
# Search for nodes by xpath
doc.xpath('//p/a').each do |a_tag|
puts a_tag.content
end
####
# Or mix and match.
doc.search('//p/a', 'p > a').each do |a_tag|
puts a_tag.content
end
###
# Find attributes and their values
# doc.search('a').first['href']
●例2
require 'rubygems'
require 'open-uri'
require 'nokogiri'
# Perform a google search
doc = Nokogiri::HTML(open('http://google.com/search?q=tenderlove'))
puts doc
# Print out each link using a CSS selector
# doc.css('h3.r > a.l').each do |link|
doc.css('h3').each do |link|
puts link.content
end
0 件のコメント:
コメントを投稿