Nokogiri: how to search for certain element, and output the full traverse? [closed]

StackOverflow https://stackoverflow.com/questions/1484779

  •  18-09-2019
  •  | 
  •  

Question

using nokogiri,

i want to find <p class="main"> Some text here...</p>

from an html document,

and then output the location as below or something that shows the tree

html > body > div class = "body" > p class= "main "
Was it helpful?

Solution

text="<html><body><div class='body'><p class='main'>some text here</p></div></body></html>"
doc = Nokogiri::HTML(text)
root = doc.root
node = doc.xpath('//p[@class="main"]').first
path = [node]
begin
  node = node.parent
  path.unshift node
end until node == root
path.map {|n| n.name}.join " > "

Exercise for you to add whichever attributes you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top