1

I am extracting a page with Nokogiri which returns a Nokogiri::XML::NodeSet. From this, I would like to extract only the text from even nodes.

doc.search("h2 a").class #=> Nokogiri::XML::NodeSet
doc.search("h2 a").count #=> returns 148

I am interested in 0,2,4,8, etc.:

doc.search("h2 a")[0].text #=> the one I wanted.
doc.search("h2 a")[2].text #=> the one I wanted.

2 Answers 2

6

Try the below :

doc.search("h2 a").map.with_index(0) do |i,nd|
    i.text if nd.even?
end.compact
0
3

Maybe you want every even-positioned a node:

doc.search("h2 a:nth-child(even)")

or perhaps you are looking for every other node over all:

doc.search("h2 a").select.with_index{|a, i| i.even?}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.