How can you manipulate the html page rendered through Nokogiri?

so i parsed the html page using nokogiri.

I want to wrap tags around every link appearing

.wrap()

It does not work properly.

puts doc.xpath("//a").wrap("<b></b>");

      

returns normal plain unchanged html.

+2


source to share


1 answer


This is a flaw in the way of working wrap

. Here is the source:

# File lib/nokogiri/xml/node_set.rb, line 212
  def wrap(html, &blk)
    each do |j|
      new_parent = Nokogiri.make(html, &blk)
      j.parent.add_child(new_parent)
      new_parent.add_child(j)
    end
    self
  end

      



As you can see, instead of replacing it j

with, new_parent

it adds siblings new_parent

to the end j

. You can do what you want:

doc.search('//a').each do |j|
  new_parent = Nokogiri::XML::Node.new('b',doc)
  j.replace  new_parent
  new_parent << j
end

      

+2


source







All Articles