Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanTron/323056 to your computer and use it in GitHub Desktop.
Save JonathanTron/323056 to your computer and use it in GitHub Desktop.
# require Rubygems and Nokogiri
require "rubygems"
# => true
require "nokogiri"
# => true
# Let's try to get all the first TRs from the TBODYs (skipping the first one) in a TABLE
Nokogiri::CSS.parse("table tbody:nth-child(n+2) tr:nth-child(1)").first.to_xpath
# => "//table//tbody[(position() >= 2) and (((position()-2) mod 1) = 0)]//*[position() = 1 and self::tr]"
# Now let's get all the As direct child of a P whose class attribute finish by "facebox"
Nokogiri::CSS.parse("p > a:not([@class$=facebox])").first.to_xpath
# => "//p/a[not(substring(@class, string-length(@class) - string-length('facebox') + 1, string-length('facebox')) = 'facebox')]"
# We can even get multiple at once
Nokogiri::CSS.parse("div[@class*=comments] p[@class=comment]:last-child, a[@class*=facebox]").map{|css| css.to_xpath }
# => ["//div[contains(@class, 'comments')]//p[@class = 'comment' and last-child(.)]", "//a[contains(@class, 'facebox')]"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment