Skip to content

Instantly share code, notes, and snippets.

@flavorjones
Forked from tenderlove/gist:29107
Created November 25, 2008 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save flavorjones/29113 to your computer and use it in GitHub Desktop.
Save flavorjones/29113 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'nokogiri'
class Nokogiri::XML::Node
def method_missing name, *args, &block
if args.empty?
list = xpath("//#{name}")
elsif args.first.is_a? Hash
hash = args.first
if hash[:css]
list = css("#{name}#{hash[:css]}")
elsif hash[:xpath]
conds = Array(hash[:xpath]).collect{|j| "[#{j}]"}
list = xpath("//#{name}#{conds}")
end
else
list = css("#{name}#{args.first}")
end
list.length == 1 ? list.first : list
end
end
doc = Nokogiri::HTML(<<-eohtml)
<html>
<body>
<ul>
<li class='red'>one</li>
<li class='blue'>two</li>
</ul>
</body>
</html>
eohtml
p doc.html.body.ul.li.first.text # => one
p doc.html.body.ul.li(".blue").text # => two
p doc.html.body.ul.li(:css => ".blue").text # => two
p doc.html.body.ul.li(:xpath => "position()=2").text # => two
p doc.html.body.ul.li(:xpath => ["contains(text(),'o')"]).first.text # => one
p doc.html.body.ul.li(:xpath => ["contains(text(),'o')","contains(text(),'t')"]).text # => two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment