I am using Hpricot to select a <div> element from a web page:
doc = open("overview.html") { |f| Hpricot(f) }
puts doc.search("div[@class=leftnav-btn]")
I want to copy that element and paste it to under other <div> element with class="secondDiv".
How can I do this?
I'd do it like this:
The empty line after
<body>is the result of the trailing TextNode that follows the<div>tag. It doesn't affect how XML works, nor does it affect the data, it's only cosmetic.Notice that in the above selector I'm only using the class
.leftnav-btnsince it wasn't necessary to use the fulldiv.leftnav-btn. Nokogiri, like Hpricot, uses CSS selectors, and also allows XPath, making for more flexibility. Nokogiri also supports%and/though we don't use them:Hpricot was deprecated a long time ago, and shouldn't be used. Nokogiri is the standard for HTML/XML parsing for Ruby.
The Nokogiri tutorials cover the basics so spend some time with them. See the documentation for Nokogiri::XML::Node and Nokogiri::XML::NodeSet for more information.