2009-03-04 18 views
12

ho il seguente codice HTML:Nokogiri (rubygem): Trovare e sostituire tag HTML

<html> 
<body> 
<h1>Foo</h1> 
<p>The quick brown fox.</p> 
<h1>Bar</h1> 
<p>Jumps over the lazy dog.</p> 
</body> 
</html> 

... e utilizzando la rubygem Nokogiri (una sostituzione hpricot), mi piacerebbe cambiarlo in HTML seguente:

<html> 
<body> 
<p class="title">Foo</p> 
<p>The quick brown fox.</p> 
<p class="title">Bar</p> 
<p>Jumps over the lazy dog.</p> 
</body> 
</html> 

In altre parole: come posso trovare e sostituire determinati tag HTML utilizzando Nokogiri? So come trovarli (usando le parole chiave CSS), ma non so come sostituirli durante l'analisi del documento.

Grazie per il vostro aiuto!

risposta

18

Prova questo:

require 'nokogiri' 

html_text = "<html><body><h1>Foo</h1><p>The quick brown fox.</p><h1>Bar</h1><p>Jumps over the lazy dog.</p></body></html>" 

frag = Nokogiri::HTML(html_text) 
frag.xpath("//h1").each { |div| div.name= "p"; div.set_attribute("class" , "title") } 
+0

Questa soluzione è davvero elegante! Molte grazie! – Javier

+0

Sai come fare una ricerca in css per trovare un div con un id e una classe? Esempio:

XXX
? – Javier

+0

frag.xpath ("// div [@ id = 'foo' e @ class = 'bar']") – SimonV

15

sembra che questo funziona a destra:

require 'rubygems' 
require 'nokogiri' 

markup = Nokogiri::HTML.parse(<<-somehtml) 
<html> 
<body> 
<h1>Foo</h1> 
<p>The quick brown fox.</p> 
<h1>Bar</h1> 
<p>Jumps over the lazy dog.</p> 
</body> 
</html> 
somehtml 

markup.css('h1').each do |el| 
    el.name = 'p' 
    el.set_attribute('class','title') 
end 

puts markup.to_html 
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
# >> <html><body> 
# >> <p class="title">Foo</p> 
# >> <p>The quick brown fox.</p> 
# >> <p class="title">Bar</p> 
# >> <p>Jumps over the lazy dog.</p> 
# >> </body></html> 
+0

Anche questa soluzione funziona. – Javier

6
#!/usr/bin/env ruby 
require 'rubygems' 
gem 'nokogiri', '~> 1.2.1' 
require 'nokogiri' 

doc = Nokogiri::HTML.parse <<-HERE 
    <html> 
    <body> 
     <h1>Foo</h1> 
     <p>The quick brown fox.</p> 
     <h1>Bar</h1> 
     <p>Jumps over the lazy dog.</p> 
    </body> 
    </html> 
HERE 

doc.search('h1').each do |heading| 
    heading.name = 'p' 
    heading['class'] = 'title' 
end 

puts doc.to_html 
+0

Questa soluzione funziona. – Javier

Problemi correlati